前端:
common.js
function $(id) {
return document.getElementById(id);
}
function createXhr(){
var xhr;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject("Microsoft XMLHttp");
}
return xhr;
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="common.js"></script>
</head>
<body>
<select id="selProvince" οnchange="loadCity()"></select>
<select id="selCity"></select>
<script>
function loadProvince(){
var xhr = createXhr();
xhr.open("get","1.php",false);
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200){
var resText = xhr.responseText;
var arr = JSON.parse(resText);
console.log(arr);
var opts = "";
for(var i in arr){
opts += "<option value=" + i + ">" + arr[i] + "</option>";
}
$("selProvince").innerHTML = opts;
}
}
xhr.send(null);
}
function loadCity(){
var xhr = createXhr();
var id = $("selProvince").value;
xhr.open("get","2.php?id="+id,true);
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200){
var resText = xhr.responseText;
var arr = JSON.parse(resText);
console.log(arr);
var opts = "";
for(var i in arr){
opts += "<option value=" + i + ">" + arr[i] + "</option>";
}
$("selCity").innerHTML = opts;
}
}
xhr.send(null);
}
window.onload = function(){ //多练几遍
loadProvince();
loadCity();
}
</script>
</body>
</html>
后台:
1.php
<?php
#增加响应消息头Content-type,值为application/json
header("Content-Type:application/json");
$province = ["黑龙江","吉林","辽宁"];
$str = json_encode($province);
echo $str;
?>
2.php
<?php
header("Content-Type:application/json");
$city = [["1","11","111"],["2","22","222"],["3","33","333"]];
@$id = $_REQUEST["id"];
if($id == null || $id == ""){
die("id required");
}
echo json_encode($city[$id]);
?>
注意:
(1)xhr.open两次不同,一次是同步,一次是异步,主要是为了正确显示,提升用户体验;
(2)window.onload 提升用户体验,初次进入页面时显示正确数据;
(3)php中增加消息头,定义传输数据格式