根据数据库中另一个下拉菜单中选择的选项更新一个下拉菜单


Updating one drop down menu according to option selected in another drop down menu from database

编辑后的建议(仍未解决):

我有两个下拉菜单,一个叫国家,另一个叫城市。当用户从country下拉菜单中选择一个国家时(为了简单起见,下拉菜单将被称为DDM),我希望City DDM显示该特定国家的所有城市。

我有一个关系(称为位置)在以下简单形式的数据库(与一些条目):

id country city
    1  India  New Delhi
    2  India  Hyderabad
    3   USA    San Diego
    4   USA    Palo Alto
这是我写的代码:
<html>
<head>
<title>Admin Page</title>
</head>
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function()
    {
        $(".country").change(function()
        {
            var country=$(this).val();
            var dataString = 'country='+ country;
            alert(dataString);
            $.ajax
            ({
                type: "POST",
                url: "getcity.php",
                data: dataString,
                dataType : html,
                cache: false,
                success: function(data, textStatus)
                {
                    alert(textStatus);
                    $(".city").html(data);
                } 
            });
        });
    });
</script>
<body>
<br />
<legend><h2>Welcome Admin!</h2></legend>

<?php
include('db.php');
$sql="SELECT distinct country FROM location"; 
$result=mysqli_query($con, $sql); 
if (!$result)
{
    echo "DB Error, could not list tables'n";
    echo 'MySQL Error: ' . mysql_error();
    exit;
}
echo '<h4>Location :</h4>';
echo '<select name="loaction" class="location">';
echo '<option value="foo">'.'Choose Country'.'</option>';
while ($row=mysqli_fetch_array($result))
{
    echo '<option value='.$row[country].'>'.$row[country].'</option>';
}
echo '</select>';
?>
<h4><label>City :</label> </h4>
<select name = 'city' class = 'city'>
    <option value = 'foo' > Choose City </option>
</select>

我希望你已经费心向下滚动并看到上面的代码。getcity.php文件如下所示:

<?php
include('db.php');
if($_POST['country'])
{
    $country=$_POST['country'];
    $sql=mysql_query("select id, city from location where country='$country'");
    while($row=mysql_fetch_array($sql))
    {
        $id=$row['id'];
        $city=$row['city'];
        echo '<option value="'.$id.'">'.$city.'</option>';
    }
}

但是,即使从AJAX调用返回的状态(通过alert()看到)是'Success',我也无法在City DDM中看到任何内容。

我错过了什么?

再次感谢。

我是这样做的:

你需要两个选择器:

<select name="state" class="stateSelector" ></select>
<select name="city" class="citySelector" ></select>

和一个jQuery ajax (get)调用,它将在每次stateSelector类的选择器发生变化时触发:

$('.stateSelector').change(function(){
    $.getJSON("http://site.com/getCities/"+$(this).val()+"/all",{}, function(j){
        var options = '<option value="0">- CITY -</option>';
        for (var i = 0; i < j.length; i++) {
            options += '<option value="' + j[i].id + '">' + j[i].name + '</option>';
        }
        $('.citySelector').html(options);
        $('.citySelector').prop("selectedIndex", 0);
    });
});

在服务器端,您需要调用一个url (http://site.com/getCities/{stateId}),它将接收状态id并返回包含该特定状态的所有城市的JSON集合,在本例中,JSON结构具有id (j[i].id)和name (j[i].name)。

你肯定需要使用JavaScript。
我建议使用jQuery,这样您就可以处理国家列表中的事件更改,并使其向服务器发送ajax调用,并将结果作为json对象获取,例如:

{
  'country':{
     'id' :10,
     'name' 'France',
     ...
     'cities':{
        '1':'lille',
        '2':'paris'
        ...
     }
  }
}

使用json-encode将结果编码为php中的json对象。并使用.html更改第二个列表中的城市。

$(".cities_list").html("<option name='1'>lille</option><option name='2'>france</option> ...");

这里有一个例子

必须使用AJAX从数据库

设置选项

在你的视图文件中:

<script>
$(document).ready(function(){
    $("#yourCountryDropDownID").live("change", function(){
        var country = $(this).val();
        $.ajax({
            type: "GET",
            url: "yourSiteUrl/getCities.php/?country="+country,
            success: function(data){
               $("#city_div").html(data);
            }
        });
    });
})
</script>

您的城市下拉列表应该在id为city_div的div中。现在创建一个PHP文件getCities.php,并将下面的代码放入其中。

if(isset($_GET["country"]) && !empty($_GET["country"])){
    //Your Code
    //to get cities from country id
    // will come here
}

不要忘记在视图中导入jQuery

这是你的代码的工作版本:

<html>
<head>
<title>Admin Page</title>
</head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function()
    {
        $('.country').change(function(){
            $.get("http://172.17.0.2/getcity.php?country="+$(this).val(),{}, function(data){
                $('.city').html(data);
                $('.city').prop("selectedIndex", 0);
            });
        });         
    });
</script>
<body>
<br />
<legend><h2>Welcome Admin!</h2></legend>

<?php
$rows = array( 
                array('country' => 'India'), 
                array('country' => 'Brazil')
            );
echo '<h4>Location :</h4>';
echo '<select name="country" class="country">';
foreach ($rows as  $row)
{
    echo '<option value='.$row['country'].'>'.$row['country'].'</option>';
}
echo '</select>';
?>
<h4><label>City :</label> </h4>
<select name = 'city' class = 'city'>
    <option value = 'foo' > Choose City </option>
</select>

这是ajax调用的脚本(getcity.php):

<?php
include('db.php');
if($_GET['country'])
{
        $rows = array( 
                array('country' => 'India', 'city' => 'Nova Delhi'), 
                array('country' => 'Brazil', 'city' => 'Rio de Janeiro')
            );
    foreach($rows as $row)
    {
        if($row['country'] == $_GET['country']) {
            echo '<option value="'.$row['city'].'">'.$row['city'].'</option>';
        }
    }
}

在浏览器中使用此脚本进行测试:

http://172.17.0.2/cityAjax.php?country=Brazil

在Chrome中你可以直接输入

view-source:http://172.17.0.2/getcity.php?country=Brazil

这个调用的源代码应该是:

<option value="Rio de Janeiro">Rio de Janeiro</option>

当然,您必须编辑主机ip地址172.17.0.2。:)