Ajax实现城市二级联动(三)
本文实例为大家分享了Ajax实现城市二级联动的具体代码,供大家参考,具体内容如下
这是Ajax实现城市二级联动系列文章第三篇,把之前2篇整合在一起
1、html
<selectid="province"> <option>请选择</option> </select> <selectid="city"> <option>请选择</option> </select>
2、javascript
//创建获取ajax核心对象的函数
functiongetXhr(){
varxhr=null;
if(window.XMLHttpRequest){
xhr=newXMLHttpRequest();
}else{
xhr=newActiveXObject("Microsoft.XMLHttp");
}
returnxhr;
}
varxhr=getXhr();
//第一次执行Ajax异步请求-省份
window.onload=function(){
xhr.open("get","finaly.php?state=1");
xhr.send(null);
xhr.onreadystatechange=function(){
if(xhr.readyState==4&&xhr.status==200){
vardata=xhr.responseText;
//将字符串转换为数组
varprovinces=data.split(",");
//遍历数组
for(vari=0;i<provinces.length;i++){
//创建option元素添加到id为province元素上
varoption=document.createElement("option");
vartext=document.createTextNode(provinces[i]);
option.appendChild(text);
varprovince=document.getElementById("province");
province.appendChild(option);
}
}
}
};
//第二次执行Ajax异步请求-城市
varprovince=document.getElementById("province");
province.onchange=function(){
varcity=document.getElementById("city");
varopts=city.getElementsByTagName("option");
for(varz=opts.length-1;z>0;z--){
city.removeChild(opts[z]);
}
if(province.value!="请选择"){
xhr.open("post","finaly.php");
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send("state=2&province="+province.value);
xhr.onreadystatechange=function(){
if(xhr.readyState==4&&xhr.status==200){
vardata=xhr.responseText;
varcities=data.split(",");
for(vari=0;i<cities.length;i++){
varoption=document.createElement("option");
vartext=document.createTextNode(cities[i]);
option.appendChild(text);
city.appendChild(option);
}
}
}
}
};
3、finaly.php
<?php
//接收客户端发送的请求数据-state
$state=$_REQUEST['state'];
//判断$state的值
if($state==1){//获取省份
echo'山东省,辽宁省,吉林省';
}else{//获取城市
$province=$_POST['province'];
switch($province){
case'山东省':
echo'青岛市,济南市,威海市,日照市,德州市';
break;
case'辽宁省':
echo'沈阳市,大连市,铁岭市,丹东市,锦州市';
break;
case'吉林省':
echo'长春市,松原市,吉林市,通化市,四平市';
break;
}
}
?>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。