用jQuery的ajax方法,结合PHP,轻松实现省市级的二级联动:
新建area.php
<?
$dbc=mysqli_connect("localhost","xxxx","xxxxxxxxxx","test") or die("can not connect to mysql ".mysqli_error());
mysqli_query($dbc,"set names utf8");
header("Content-Type:text/html;charset=utf-8");
if($_REQUEST['do']=="search" && $_REQUEST['pid']){
$str="";
$str='<select id="down_area" name="down_area">';
$r="select areaid,name from `china_areas` where parentid='".$_REQUEST['pid']."' order by vieworder asc;";
$q=mysqli_query($dbc,$r);
while(list($areaid,$name)=mysqli_fetch_array($q,MYSQLI_NUM)){
$str.='<option value="'.$areaid.'">'.$name.'</option>';
}
$str.='</select>';
echo $str;exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无刷新二级联动</title>
<script src="js/jquery-1.6.2.min.js" type="text/javascript"></script>
<script language="javascript">
function down_area(obj){
$.ajax({
type: "POST",
url: "area.php",
data: "do=search&pid="+obj.value,
success: function(msg){
$("#area_list").html(msg);
}
});
}
</script>
<style>
body{font:12px Arial, "微软雅黑", sans-serif;color:#666;line-height:22px;}
</style>
</head>
<body>
<p style="height:250px;"> </p>
<div align="center">
地区:
<select id="area" name="area" οnchange="down_area(this);">
<?
$r="select areaid,name from `china_areas` where parentid='0' order by vieworder asc;";
$q=mysqli_query($dbc,$r);
while(list($areaid,$name)=mysqli_fetch_array($q,MYSQLI_NUM)){
?>
<option value="<?=$areaid;?>"><?=$name;?></option>
<?
}
?>
</select> <span id="area_list"></span>
</div>
</body>
效果如图:
下拉选择广东省后: