写个Ajax三级联动实例,用的最新的全国省市县mysql数据。这里只说一下思路,具体请看源码。
首先看index.php,这是一个省份列表
$conn=mysql_connect("localhost","root","");
mysql_select_db("china");
mysql_query("set names 'utf8'");
$sql="select * from t_province order by ProSort ASC";
$result=mysql_query($sql);
echo "\n";
echo "\n";
echo "请选择省份\n";
while($row=mysql_fetch_row($result)){
echo "$row[1]\n";
}
echo "\n";
echo "\n";
echo "\n";
echo "\n";
?>
还有两个javascript代码作用是传递省份主键值和城市主键值到ajax.php中查询数据。
function queryCity(province){
createXMLHttpRequest();
type="city";
var url="ajax.php?type=province&province="+province;
xmlHttp.open("GET",url,true);
xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.send(null);
}
function queryArea(city){
createXMLHttpRequest();
type="area";
var url="ajax.php?type=city&city="+city;
xmlHttp.open("GET",url,true);
xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.send(null);
}
ajax.php文件就是接受传递过来的数据并查询相关市县。
// 根据传递的省份ID值查询t_city表中ProID值为该省份ID的城市。
if($_GET['type']=='province'){
if(!empty($_GET['province'])){
$province = intval($_GET['province']);
$sql="select * from `t_city` where `ProID` = '$province' ";
$result=mysql_query($sql);
echo "\n";
echo "请选择城市\n";
while($row=mysql_fetch_row($result)){
echo "$row[1]\n";
}
echo "\n";
}
}
// 根据传递的城市ID值查询t_district表中CityID值为该市ID的城市。
if($_GET['type']=='city'){
if(!empty($_GET['city'])){
$city = intval($_GET['city']);
$sql="select * from `t_district` where `CityID` = '$city'";
$result=mysql_query($sql);
echo "\n";
echo "请选择县\n";
while($row=mysql_fetch_row($result)){
echo "$row[1]\n";
}
echo "\n";
}
}