index.html
<html>
<head>
<Meta charset="utf-8">
<script>
function getArea(val,table){
var xhr;
if(window.ActiveXObject){
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}else if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}
var url = "ajax.PHP";
xhr.open("POST",url,true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.onreadystatechange = callback;
xhr.send("val="+val+"&table="+table);
function callback(){
if(xhr.readyState==4){
if(xhr.status ==200){
//alert(xhr.responseText);
document.getElementById(table).innerHTML = xhr.responseText;
}
}
}
}
</script>
</head>
<body onLoad="getArea('','t_province')">
<select id="t_province" onChange="getArea(this.value,'t_city')"></select>省
<select id="t_city" onChange="getArea(this.value,'t_district')"></select>市
<select id="t_district"></select>县
</body>
</html>
ajax.PHP
<?PHP MysqL_connect('localhost','root','123'); MysqL_select_db('china'); MysqL_query("set names utf8"); //获得用户点击的值以及应该显示的表明 $val = $_POST['val']; $table = $_POST['table']; if($table == 't_province'){ //查询所有的省 $sql = "select ProName from $table order by ProSort"; $result = MysqL_query($sql); $rows = array(); while($row = MysqL_fetch_row($result)){ echo "<option>$row[0]</option>"; } }else if($table =='t_city'){ //已知 ProName 查询对应的市的名字 $sql = "select CityName from t_city where ProID=(select ProID from t_province where ProName = '$val')"; $result = MysqL_query($sql); $rows = array(); while($row = MysqL_fetch_row($result)){ echo "<option>$row[0]</option>"; } }else if($table =='t_district'){ //已知 CityName 查询对应的县的名字 $sql = "select DisName from t_district where CityID=(select CityID from t_city where CityName = '$val')"; $result = MysqL_query($sql); $rows = array(); while($row = MysqL_fetch_row($result)){ echo "<option>$row[0]</option>"; } } ?>
原文链接:https://www.f2er.com/ajax/166659.html