如何使用jQuery在PHP中创建级联下拉列表
我的数据库由国家和城市组成 第一个案例-成功完成:如何使用jQuery在PHP中创建级联下拉列表,php,ajax,jquery,Php,Ajax,Jquery,我的数据库由国家和城市组成 第一个案例-成功完成: 国家/地区列表在页面加载时填充到下拉框中 城市列表在页面加载填充城市列表的下拉框中填充 基于默认国家/地区 第二种情况-无法成功: 用户更改国家/地区 城市列表将根据所选国家/地区进行更改 我知道我必须使用jQuery/Ajax。我试过了,但由于缺乏编程经验,我无法解决我的问题。我的列表是从数据库中获取的,不是XML。我只是需要一个快速的解决方案,我需要保持它简单和愚蠢 我使用的是常规的PHP编码风格,而不是面向对象的 我怎么做?任何相关资源都
我怎么做?任何相关资源都将不胜感激。您可以使用jquery的
.change()
方法对选择框值进行更改时进行ajax调用 写入数据而不是obj。它工作得非常好index.php
堆栈溢出
请检查您的代码-您混淆了变量数据和obj。
$("#country").change(function(){
$('#city').find('option').remove().end(); //clear the city ddl
var country = $(this).find("option:selected").text();
alert(country);
//do the ajax call
$.ajax({
url:'getCity.php'
type:'GET',
data:{city:country},
dataType:'json',
cache:false,
success:function(data){
data=JSON.parse(data); //no need if dataType is set to json
var ddl = document.getElementById('city');
for(var c=0;c<obj.length;c++)
{
var option = document.createElement('option');
option.value = obj[c];
option.text = obj[c];
ddl.appendChild(option);
}
},
error:function(jxhr){
alert(jxhr.responseText);
}
});
});
$country = $_GET['city'];
//do the db query here
$query = "your query";
$result = mysql_query($query);
$temp = array();
while ($row = mysql_fetch_assoc($result)) {
if(empty($temp))
{
$temp=array($row['city']);
}
else
{
array_push($temp,$row['city']);
}
}
echo (json_encode($temp));