首页 > 代码库 > PHP+Ajax+JS省市区三级联动
PHP+Ajax+JS省市区三级联动
基本思想就是:在JS动态创建select控件的option,通过Ajax获取在PHP从SQL数据库获取的省市区信息,代码有点长,但很多都是类似的,例如JS中省、市、区获取方法类似,PHP中通过参数不同执行不同的select语句。
index.html代码:
<!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>
<title>PHP+Ajax获取SQL数据库</title>
<META http-equiv=Content-Type content="text/html; charset=gb2312">
<script src="http://www.mamicode.com/scripts/thumbnails.js" type="text/javascript"></script>
</head>
<body>
<div id="description">
<select style="width:100px; " onchange="sech(this.id)" id="sheng">
<option value="http://www.mamicode.com/province">请选择省份</option>
</select>
<select onchange="sech(this.id)" id="shi">
<option value="http://www.mamicode.com/city">请选择市区</option>
</select>
<select id="xian">
<option value="http://www.mamicode.com/county">请选择县乡</option>
</select>
</div>
</div>
</body>
</html>
<?php
header("Content-Type: text/html; charset=gb2312");
$conn = new COM("ADODB.Connection") or die("Cannot start ADO");
$connstr = "Provider=SQLOLEDB;Persist Security Info=False;User ID=sa;Password=zzh;Initial Catalog=NoteBook;Data Source=localhost";
if($_REQUEST[‘ID‘]==0){//获得省列表
$conn->Open($connstr); //建立数据库连接
$sqlstr = "select name from Province"; //设置查询字符串
$rs = $conn->Execute($sqlstr); //执行查询获得结果
$num_cols = $rs->Fields->Count(); //得到数据集列数
$Province=array();
$i=0;
while (!$rs->EOF) {
$Province[$i]=$rs->Fields[‘name‘]->Value.",";
$rs->MoveNext();
$i++;
}
foreach($Province as $val)
echo $val;
$conn->Close();
$rs = null;
$conn = null;
}
if($_REQUEST[‘ID‘]>0&&$_REQUEST[‘ID‘]<35){//获得省对应的市列表
$conn->Open($connstr); //建立数据库连接
$sqlstr = "select name from City where cid=".$_REQUEST[‘ID‘]; //设置查询字符串
$rs = $conn->Execute($sqlstr); //执行查询获得结果
$num_cols = $rs->Fields->Count(); //得到数据集列数
$City=array();
$i=0;
while (!$rs->EOF) {
$City[$i]=$rs->Fields[‘name‘]->Value.",";
$rs->MoveNext();
$i++;
}
foreach($City as $val)
echo $val;
$conn->Close();
$rs = null;
$conn = null;
}
if($_REQUEST[‘ID‘]>100){//获得省市对应的县列表
$conn->Open($connstr); //建立数据库连接
$sqlstr = "select name from County where cid=".$_REQUEST[‘ID‘]; //设置查询字符串
$rs = $conn->Execute($sqlstr); //执行查询获得结果
$num_cols = $rs->Fields->Count(); //得到数据集列数
$County=array();
$i=0;
while (!$rs->EOF) {
$County[$i]=$rs->Fields[‘name‘]->Value.",";
$rs->MoveNext();
$i++;
}
foreach($County as $val)
echo $val;
$conn->Close();
$rs = null;
$conn = null;
}
?>