欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Ajax實(shí)現(xiàn)城市二級(jí)聯(lián)動(dòng)(三)

 更新時(shí)間:2017年02月20日 09:05:42   作者:九成  
這篇文章主要為大家詳細(xì)介紹了Ajax實(shí)現(xiàn)城市二級(jí)聯(lián)動(dòng)的方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了Ajax實(shí)現(xiàn)城市二級(jí)聯(lián)動(dòng)的具體代碼,供大家參考,具體內(nèi)容如下

這是Ajax實(shí)現(xiàn)城市二級(jí)聯(lián)動(dòng)系列文章第三篇,把之前2篇整合在一起

1、html

<select id="province">
 <option>請(qǐng)選擇</option>
 </select>
 <select id="city">
 <option>請(qǐng)選擇</option>
 </select>

2、javascript

//創(chuàng)建獲取ajax核心對(duì)象的函數(shù)
  function getXhr(){
   var xhr = null;
   if(window.XMLHttpRequest){
    xhr = new XMLHttpRequest();
   }else{
    xhr = new ActiveXObject("Microsoft.XMLHttp");
   }
   return xhr;
  }
  var xhr = getXhr();
  // 第一次執(zhí)行Ajax異步請(qǐng)求 - 省份
  window.onload = function(){
   xhr.open("get","finaly.php?state=1");
   xhr.send(null);
   xhr.onreadystatechange = function(){
   if(xhr.readyState==4&&xhr.status==200){
     var data = xhr.responseText;
     // 將字符串轉(zhuǎn)換為數(shù)組
     var provinces = data.split(",");
     // 遍歷數(shù)組
     for(var i=0;i<provinces.length;i++){
      // 創(chuàng)建option元素添加到id為province元素上
      var option = document.createElement("option");
      var text = document.createTextNode(provinces[i]);
      option.appendChild(text);
      var province = document.getElementById("province");
      province.appendChild(option);
     }
    } 
   }
  };
  // 第二次執(zhí)行Ajax異步請(qǐng)求 - 城市
  var province=document.getElementById("province");
  province.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(province.value != "請(qǐng)選擇"){
    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){
      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);
      }
     }
    }
   }
  };

3、finaly.php

<?php
 // 接收客戶端發(fā)送的請(qǐng)求數(shù)據(jù) - state
 $state = $_REQUEST['state'];
 // 判斷$state的值
 if($state == 1){// 獲取省份
  echo '山東省,遼寧省,吉林省';
 }else{// 獲取城市
  $province = $_POST['province'];
  switch ($province){
   case '山東省':
    echo '青島市,濟(jì)南市,威海市,日照市,德州市';
    break;
   case '遼寧省':
    echo '沈陽(yáng)市,大連市,鐵嶺市,丹東市,錦州市';
    break;
   case '吉林省':
    echo '長(zhǎng)春市,松原市,吉林市,通化市,四平市';
    break;
  }
 }
?>

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論