ajax实现二级联动

来源:互联网 发布:vscode怎么编译运行 编辑:程序博客网 时间:2024/05/16 11:42
<!doctype html>
<html>
 <head>
  <meta charset="utf-8">
  <title>二级联动</title>
 </head>
 <body>
  <select id="province">
      <option>请选择</option>
</select>
<select id="city">
<option>请选择</option>
</select>
<script>
var xhr=getXhr();

     window.onload=function(){
  xhr.open("get","08.php?state=1");
  xhr.send(null);
  xhr.onreadystatechange=function(){
          if(xhr.readyState==4&&xhr.status==200){
             var data=xhr.responseText;
var provinces=data.split(",");
 for(var i=0;i<provinces.length;i++){
                 var option=document.createElement("option");
var text=document.createTextNode(provinces[i]);
  option.appendChild(text);

  var province=docuemnt.getElementById("province");
   province.appendChild(province); 
 }
 }
  }
}

var provinceEle=document.getElementById("province");
     provinceEle.onchange=function(){
        var city=document.getElementById("city");
var opts=city.getElementsByTagName("option");
for(var z=opts.length-1;z>0;z--){
               city.removeChild(opts[z]);
}
if(provinceEle!="请选择"){        
  xhr.open("post","08.php");
  xhr.send("state=2&province="+provinceEle.value);
  xhr.onreadystatechange=function(){
            if(xhr.readyState==4&&xhr.status==200){
                var data=xhr.responseText;
var cities=data.split(",");
for(var i=0;i<cities.length;i++){
                   var option=document.createElement("option");
  var text=document.createTextNode(cities[i]);
  option.appendChild(text);
 
  city.appendChild(option);
}
}
        }
   }
     }
    function getXhr(){
       var xhr=null;
  if(window.XMLHttpRequest){
           xhr=new XMLHttpRequest();
  }else{
           xhr=new ActiveXObject('Microsoft.XMLHttp');
  }
  return xhr;
}    

</script>


08.php:

<?php
  $state=$_REQUEST['state'];
  if($state==1){
      echo '山东省,辽宁省,吉林省';
  }else{
     $province=$_POST['province'];
   switch (province){
  case "山东省":
     echo '青岛市,济南市,威海市,德州市,日照市';
     break;
  case "吉林省":
     echo '长春市,松原市,吉林市,通化市,四平市';
     break;
  case "辽宁省":
     echo '沈阳市,大连市,铁岭市,丹东市,锦州市';
 break; 
}
  }


?>


 </body>
</html>
0 0
原创粉丝点击