//創(chuàng)建獲取ajax核心對象的函數(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異步請求 - 省份
window.onload = function(){
xhr.open("get","finaly.php?state=1");
xhr.send(null);
xhr.onreadystatechange = function(){
if(xhr.readyState==4xhr.status==200){
var data = xhr.responseText;
// 將字符串轉換為數(shù)組
var provinces = data.split(",");
// 遍歷數(shù)組
for(var i=0;iprovinces.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異步請求 - 城市
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 != "請選擇"){
xhr.open("post","finaly.php");
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send("state=2province="+province.value);
xhr.onreadystatechange = function(){
if(xhr.readyState==4xhr.status==200){
var data = xhr.responseText;
var cities = data.split(",");
for(var i=0;icities.length;i++){
var option = document.createElement("option");
var text = document.createTextNode(cities[i]);
option.appendChild(text);
city.appendChild(option);
}
}
}
}
};
?php
// 接收客戶端發(fā)送的請求數(shù)據(jù) - state
$state = $_REQUEST['state'];
// 判斷$state的值
if($state == 1){// 獲取省份
echo '山東省,遼寧省,吉林省';
}else{// 獲取城市
$province = $_POST['province'];
switch ($province){
case '山東省':
echo '青島市,濟南市,威海市,日照市,德州市';
break;
case '遼寧省':
echo '沈陽市,大連市,鐵嶺市,丹東市,錦州市';
break;
case '吉林省':
echo '長春市,松原市,吉林市,通化市,四平市';
break;
}
}
?>