根据建议进行编辑(仍未解决):
我有 2 个下拉菜单,一个叫国家,另一个叫城市。当用户从“国家/地区”下拉菜单中选择一个国家时(以下为简便起见,下拉菜单将称为 DDM),我希望城市 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() 看到)是“成功”,我也看不到 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) 和姓名 (j[i].name).
关于php - 根据数据库中另一个下拉菜单中选择的选项更新一个下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16535889/