前端:
commen.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="select1" οnchange="pro2()"></select>
<select id="select2"></select>
<script>
//省市级联
function pro1(){
var xhr = createXhr();
xhr.open("get","province.php",false); //因为二级,所以这里要用同步
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200){
var resText = xhr.responseText;
console.log(resText);
$("select1").innerHTML = resText;
}
}
xhr.send(null); //这个别忘了
}
function pro2(){
var city = $("select1").value;
var xhr = createXhr();
var url = "province1.php?value="+city;
xhr.open("get",url,true);
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200){
var resText = xhr.responseText;
console.log(resText);
$("select2").innerHTML = resText;
}
}
xhr.send(null); //这个别忘了
}
window.onload = function(){ //因为异步,所以出了问题,初次进入页面时,两个可以同步执行,所以pro1()要设置成同步
pro1();
pro2();
}
</script>
</body>
</html>
后台
province.php
<?php
$arr = ["黑龙江","吉林","辽宁"];
$str = "";
for($i=0;$i<3;$i++){
$str .= "<option value='$i'>" . $arr[$i] . "</option>";
}
echo $str;
?>
province1.php
<?php
@$value = $_REQUEST["value"];
if($value == null || $value == ""){
die("value required");
}
$city = [['1','11','111'],['2','22','222'],['3','33','333']];
$str = "";
for($i=0;$i<3;$i++){
$str .= "<option value=$i>" .$city[$value][$i] . "</option>";
}
echo $str;
?>