Ajax实现的联动

来源:互联网 发布:淘宝关联页 编辑:程序博客网 时间:2024/05/08 06:17

index.js代码:

// 创建Ajax的核心对象(不兼容IE6)function getXhr(){   var xhr = null;//定义核心对象   if(window.XMLHttpRequest){//其他浏览器      xhr = new XMLHttpRequest();   }else{//IE浏览器      xhr = new ActiveXObject("Microsoft.XMLHttp");   }   return xhr;}// 创建Ajax的核心对象(兼容IE6)function getXhr2(){   var xhr = null;   try{//其他浏览器      xhr = new XMLHttpRequest();   }catch(e){//IE浏览器      try{//IE7+         xhr = new ActiveXObject("Microsoft.XMLHttp");      }catch(e){//IE6         xhr = new ActiveXObject("Msxml2.XMLHttp");      }   }   return xhr;}// 创建XML解析器function getXml(xmlString){   var xmlDoc = null;//定义XML DOM对象   if(window.DOMParser){//其他浏览器       var parser = new DOMParser();//创建解析器      xmlDoc = parser.parseFromString(xmlString,"text/xml");//利用解析器进行解析   }else{//IE浏览器       xmlDoc = new ActiveXObject("Microsoft.XMLDOM");      xmlDoc.async = false;      xmlDoc.loadXML(xmlString);   }   return xmlDoc;}

php.php代码:

<?php   $province = $_POST['province'];   switch ($province){      case "请选择":         echo '北京市,上海市,天津市';      break;      case "北京市":         echo '海淀区,万寿路,上地,中关村,天安门,动物园';      break;      case "上海市":         echo '上海市1,上海市2,上海市3,上海市4,上海市5,上海市6';      break;      case "天津市":         echo '天津市1,天津市2,天津市3,天津市4,天津市5,天津市6';      break;   }  ?>


html代码:

<!DOCTYPE html><html><head>    <meta charset="utf-8"/>    <script src="index.js"></script></head><body><select id="province">    <option>请选择</option></select><select id="city">    <option>请选择</option></select><br><br><script>    var province = document.getElementById("province");    var xhr = getXhr();    window.onload = function () {        var provinceValue = province.value;        if (provinceValue == "请选择") {            wo(province);        }    }    province.onchange = function () {        var city = document.getElementById("city");        var opts = city.options;        var len = opts.length        for (var t = 1; t < len; t++) {            city.remove(1);        }        var provinceValue = province.value;        if (provinceValue != "请选择") {            wo(city);        }    }    function ni(ha) {        if (xhr.readyState == 4 && xhr.status == 200) {            var data = xhr.responseText;            cities = data.split(",");            for (var i = 0; i < cities.length; i++) {                var citie = cities[i];                ha.add(new Option(citie));            }        }    }    function wo(ha) {        var provinceValue = province.value;        var cities;        xhr.open("post", "php.php");        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");        xhr.send("province=" + provinceValue);        xhr.onreadystatechange = function () {            ni(ha);        }    }</script></body></html>

0 0
原创粉丝点击