JS—我的第四个AJAX程序(省市级联)

前端:

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;
?>





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值