Ajax and JSON 实现省市联动

 <script type="text/javascript">
 function getXmlHttpObject() {

 var xmlHttpRequest;
 //不同的浏览器获取对象xmlhttprequest 对象方法不一样
 if (window.ActiveXObject) {

 xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");

 } else {

 xmlHttpRequest = new XMLHttpRequest();
 }

 return xmlHttpRequest;

 }
//定义xhr对象
 var myXmlHttpRequest = "";

 function getCities() {
 myXmlHttpRequest = getXmlHttpObject();
 if (myXmlHttpRequest) {
 url = "/chuli.php";
 var data = "province=" + $('sheng').value;
 myXmlHttpRequest.open("post", url, true);
 myXmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

 //指定回调函数
 myXmlHttpRequest.onreadystatechange = chuli2;
 myXmlHttpRequest.send(data);

 }
 }
//发送指令,并接受处理返回的值
 /*一个获取json长度的函数 begin*/
 function getJsonLength(jsonData) {

 var jsonLength = 0;

 for (var item in jsonData) {

 jsonLength++;

 }


 return jsonLength;

 }

 /*一个获取json长度的函数 end*/
 function chuli2() {

 if (myXmlHttpRequest.readyState == 4 && myXmlHttpRequest.status==200) {
 var mes = myXmlHttpRequest.responseText;
 var mes_obj = eval("(" + mes + ")");
 var mes_objLength = getJsonLength(mes_obj);
 $('city').length = 0;
 var myOption = document.createElement("option");
 myOption.innerText = "--城市--";
 $('city').appendChild(myOption);
 for (var i = 0; i < mes_objLength; i++) {

 var abc = "a" + i;
 var city = "city" + i;
 var myOption = document.createElement("option");
 myOption.value = city;
 myOption.innerText = mes_obj[city];
 $('city').appendChild(myOption);

 }






 }
 }
//处理返回的值
 function $(id) {
 return document.getElementById(id);
 }
//一个jq一样定义的函数
 </script>

附录:

//得到json的长度,需要这个专门的函数才可以,参考链接:http://caibaojian.com/json-length.html

getjsonlength

chuli.php  内文本


<?php
//这里两句话很重要,第一讲话告诉浏览器返回的数据是xml格式
header("Content-Type: text/html;charset=utf-8");
//告诉浏览器不要缓存数据
header("Cache-Control: no-cache");

$province=$_POST['province'];

$info="";
if($province=="zhejiang"){
$info='{
"city0":"浙江城市0",
"city1":"浙江城市1",
"city2":"浙江城市2",
"city3":"浙江城市3"}';

}else if($province=="jiangsu"){
$info='{
"city0":"江苏城市0",
"city1":"江苏城市1",
"city2":"江苏城市2",
"city3":"江苏城市3"}';
}
echo $info;

?>

发表评论

电子邮件地址不会被公开。 必填项已用*标注