Cascade下拉列表使用jQuery / PHP

时间:2011-08-21 09:06:47

标签: php jquery

问题:我有国家/地区下拉列表和区域下拉列表。区域下拉列表应使用jQuery填充基于所选国家/地区的值。我用Google搜索并试图解决这个问题,但我失败了,我无法做到。任何简单的步骤可以帮助我实现这一目标?

这是我的代码:

基本上,第一页加载将从db填充drodown列表并存储 会话中的列表,因此只要会话,列表就可以在应用程序级别重复使用 很活跃。

默认countryID和regionID放在会话中,名为$ _SESSION ['regionID']和$ _SESSION ['countryID']

    if(!isset($_SESSION['countryList']))
    {
        $_SESSION['countryList'] = array();
    }

    if(!isset($_SESSION['regionList']))
    {
        $_SESSION['regionList'] = array();
    }

.
.
.
        <form action="index.php" method="GET">
            <label for="lbl_country" id="countrylabel">Country</label>
            <select name="country" id="countrylist" onchange="getRegions(<?php $_SESSION['regionID']; ?>)">
                 <?php
                    //fetch country list from database and store it in session      
                    if(isset($_SESSION['countryList']) && !empty($_SESSION['countryList']))
                    {
                        foreach ($_SESSION['countryList'] as $val)
                        {
                            echo '<option value="'.$val['countryID'].'"';
                            if($_SESSION['countryID'] == $val['countryID'])
                            {
                                echo 'selected';    
                            }
                            echo ">".$val['countryName']."</option>'";
                        }   
                    }
                    else //means the session is not set yet-or-session is empty. Either case, we have to fetch
                    {
                        $query = "SELECT countryID, countryName FROM Country ORDER BY countryID ASC";
                        $results = mysql_query($query);
                        while ($row = mysql_fetch_assoc($results)) 
                        {
                            echo '<option value="'.$row['countryID'].'"';
                            if($_SESSION['countryID'] == $row['countryID'])
                            {
                                echo 'selected';    
                            }
                            echo ">".$row['countryName']."</option>'";

                            $_SESSION['countryList'][] = $row;
                        }   
                    }                   
                ?>
            </select>

            <label for="lbl_region" id="regionlabel">Region</label>
            <select name="region" id="regionlist">
                  <?php     
                    if(isset($_SESSION['regionList']) && !empty($_SESSION['regionList']))
                    {
                        foreach ($_SESSION['regionList'] as $val)
                        {
                            echo '<option value="'.$val['regionID'].'"';
                            if($_SESSION['regionID'] == $val['regionID'])
                            {
                                echo 'selected';    
                            }
                            echo ">".$val['regionName']."</option>'";
                        }   
                    }
                    else
                    {
                        $query = "SELECT regionID, countryID, regionName FROM Region WHERE countryID =".$_SESSION['countryID']." ORDER BY regionID ASC";
                        $results = mysql_query($query);
                        while ($row = mysql_fetch_assoc($results)) 
                        {
                            echo '<option value="'.$row['regionID'].'"';
                            if($_SESSION['regionID'] == $row['regionID'])
                            {
                                echo 'selected';    
                            }
                            echo ">".$row['regionName']."</option>'";

                            //everytime you go to a loop, make sure to put the result in the session
                            $_SESSION['regionList'][] = $row;
                        }   
                    }
                ?>
            </select>
</form>

1 个答案:

答案 0 :(得分:1)

让我们举一个简单的例子,我正在使用它,它完全正常。

这是国家/地区下拉列表:

<?php
        $countrylist=mysql_query("SELECT * FROM country ORDER BY name ASC");
        echo "<select name='country' id='country' onchange=\"reload(this.form)\" title='Country e:g; United Kingdom,Pakistan'><option value='0'>Select Country</option>";
        while($clist=mysql_fetch_array($countrylist))
        {
        echo "<option value='$clist[Name]'>$clist[Name]</option>"."<br/>";
        }
        echo "</select>";
 ?>

这是区域下拉列表:

<select name="region" id="region" ></select>

现在创建一个名为crlist.js的单独文件,并将其包含在具有以下代码的页面中:

<script  type="text/javascript" src="crlist.js"> </script>

crlist.js的代码:

var request = false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
request = false;
}
}
@end @*/
function fillSelect(country,path) {
var url = path+"crlist.php?country=" + country;
request.open("GET", url, true);
request.onreadystatechange = go;
request.send(null);
}

function go() {
if (request.readyState == 4) {
//if (request.status == 200) {

var response = request.responseText;

var list=document.getElementById("region");
            for (i = list.length - 1; i>=0; i--) {
                list.remove(i);
            }
var records=response.split('|');
for (i=1; i<records.length; i++) {
    //alert("rcord="+records[i]);
    var record=records[i].split('*');
    var region=record[0];
    //alert("region="+region);
    var regionid=record[1];
    //alert("regionid="+regionid);
    var x=document.createElement('option');
    //var y=document.createTextNode(region);
    x.text=region;
    //x.value=region;
    //alert(x.text);
   //x.appendChild(y);
   //list.appendChild(x);
   list.options.add(x);
   }
  //}
 }
}

function initCs(path) {

if (!request && typeof XMLHttpRequest != 'undefined') {
request = new XMLHttpRequest();
}
var country=document.getElementById('country');
    country.onchange=function() {

        if(this.value!="Select") {

            var list=document.getElementById("region");
            for (i = list.length - 1; i>=0; i--) {
                list.remove(i);
            }
        //while (list.childNodes[0]) {
        //list.removeChild(list.childNodes[0]);
        //}
        }
        fillSelect(this.value,path);
        //alert(this.value);

    }
//fillSelect(country.value);
}

现在创建一个名为crlist.php的单独文件。

crlist.php的代码:

<?php
require_once 'yourconfigfile.php';

$cname = $_GET['country'];

$query="select ID,Name from city where CountryCode=(select code from country where name='$cname') Order By Name ASC";
$res = mysql_query($query) or die(mysql_error());
while($region = mysql_fetch_array($res)){
    echo "<option value='".$region['Name']."'>".$region['Name']."</option>";
}       
?>

现在在有下拉列表的页面上添加以下脚本:

<script  type="text/javascript" src="crlist.js"> </script>
<script>
$(document).ready(function() {

    initCs("");

});
</script>

这是我自己的脚本,我假设你已经创建了国家和地区表。但是你需要根据你的数据库结构调整查询和上面的代码。

希望这有帮助。

相关问题