如何使使用jQuery的PHP在级联下拉列表 [英] How to make a Cascading Drop Down List in PHP using jQuery
问题描述
我的数据库由国家和城市。
第一案 - 做成功了:
- 国家列表被填充在下拉框在页面加载
- 在城市列表被填充在下拉框在页面加载 - 填充城市名单 基于默认的国家。
第二种情况 - 不能使它:
- 在用户更改国家
- 在城市列表会根据选定的国家改变
我知道我必须使用jQuery /阿贾克斯。我试过,但我没能解决我的问题,由于我缺乏编程经验。我的名单是从数据库不是XML牵强。我只是需要一个快速的解决方案,我需要保持它的简单和愚蠢的。
我使用的是普通的PHP代码风格,而不是面向对象的。
我怎样才能做到这一点?任何相关的资源将接入点preciated。
$(#国)。改变(函数(){
$('#城市)找到('选项')删除()()结束。; //清除城市DDL
VAR国家= $(本).find(选项:选择)文本()。
警报(国家);
//做Ajax调用
$阿贾克斯({
网址:getCity.php
键入:GET,
数据:{城市:国家},
数据类型:JSON,
缓存:假的,
成功:功能(数据){
数据= JSON.parse(数据); //没有必要,如果数据类型设置为JSON
VAR DDL =的document.getElementById(城市);
为(变种C = 0;℃下obj.length; C ++)
{
VAR选项= document.createElement方法('选项');
option.value = OBJ [C]。
option.text = OBJ [C]。
ddl.appendChild(选件);
}
},
错误:函数(jxhr){
警报(jxhr.responseText);
}
});
});
在你的getCity.php
$国家= $ _GET ['城市'];
//做数据库查询这里
$查询=您的查询;
$结果= mysql_query($查询);
$ TEMP =阵列();
而($行= mysql_fetch_assoc($结果)){
如果(空($ TEMP))
{
$ TEMP =阵列($行['城市']);
}
其他
{
array_push($温度,$行['城市']);
}
}
回声(json_en code($ TEMP));
I have database consists of countries and cities.
First Case - Successfully done:
- Country list gets populated in drop box on page load
- City list gets populated in drop box on page load - populated city list is based on the default country.
Second Case - Couldn't make it:
- User changes country
- City list will be changed according to selected country
I know i have to use jQuery/Ajax. I tried but i couldn't solve my problem due to my lack of programming experience. My list is fetched from database not XML. I just need a quick solution, i need to keep it simple and stupid.
I'm using regular PHP coding style, not Object-Oriented.
How can i do it? Any related resources will be appreciated.
$("#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);
}
});
});
in your getCity.php
$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));
这篇关于如何使使用jQuery的PHP在级联下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!