以JQuery为JS,写的Ajax省市联动。

代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>无标题页</title> <script src="Script/jquery-1.10.2.js" type="text/javascript"></script> <script src="Script/Common.js" type="text/javascript"></script> <script type="text/javascript">
var xhr=false;
var proSel=false;//selPro
var citySel=false;//selCity
var Pid=false;
$(function(){ xhr=createXhr(); proSel=$('#selPro');
citySel=$('#selCity'); //加载省下拉框数据
getAreaData(0); //省下拉框发生改变时,加载市下拉框数据
proSel.change(function(){
Pid=$(this).val();
getAreaData(Pid);
}); }); //1.
function getAreaData(pId){
//1.open
xhr.open('get','1-getAreaData.ashx?pid='+pId,true);
//2.set
xhr.setRequestHeader('If-Modified-since',0);
//3.onreadystatechange
xhr.onreadystatechange=function(){ if(xhr.readyState==4){
if(xhr.Status==200){
var res=xhr.responseText;
if (pId==0){
data2Sel(res,proSel);
//首次加载时,加载市下拉框数据
pId=$(':selected').val();
getAreaData(pId);
}else{
data2Sel(res,citySel);
} }
}
}; xhr.send();
} //2.
function data2Sel(data,selOption){
selOption.empty(); var res=eval(data); for(var i=0;i<res.length;i++){
var opt=false;
if(i==2){
opt=$('<option value='+res[i].Id+' selected=true>'+res[i].Name+'</option>');
}else{
opt=$('<option value='+res[i].Id+'>'+res[i].Name+'</option>');
}
selOption.append(opt);
}
} </script> </head>
<body>
<select id="selPro">
</select>
<select id="selCity">
</select>
</body>
</html>
04-29 01:27