PHP+Mysql+Ajax+JS實現省市區三級聯動_PHP教程

來源:互聯網
上載者:User
基本思想就是:在JS動態建立select控制項的option,通過Ajax擷取在PHP從SQL資料庫擷取的省市區資訊,代碼有點長,但很多都是類似的,例如JS中省、市、區擷取方法類似,PHP中通過參數不同執行不同的select語句。

index.html代碼:

複製代碼 代碼如下:
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


省市區三級聯動



請選擇省份
請選擇市區
請選擇縣鄉




thumbnails.js代碼:

複製代碼 代碼如下:
window.onload = getProvince;

function createRequest() {//Ajax於PHP互動需要對象
try {
request = new XMLHttpRequest();//建立一個新的請求對象;
} catch (tryMS) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (otherMS) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = null;
}
}
}
return request;
}

function sech(id) {//省市改變時觸發,select的onchange事件

var aa = document.getElementById(id);
if(id=="sheng"){
getCity(aa.value);//這裡aa.value為省的id
}
if(id=="shi")
{
getCounty(aa.value);//這裡aa.value為市的id
}

}

function getProvince() {//擷取所有省
request = createRequest();
if (request == null) {
alert("Unable to create request");
return;
}
var url= "getDetails.php?ID=0";//ID=0時傳遞至PHP時讓其擷取所有省
request.open("GET", url, true);
request.onreadystatechange = displayProvince; //設定回呼函數
request.send(null); //發送請求
}

function getCity(id){//擷取省對應的市
request = createRequest();
if (request == null) {
alert("Unable to create request");
return;
}
var url= "getDetails.php?ID=" + escape(id);
request.open("GET", url, true);
request.onreadystatechange = displayCity;
request.send(null);
}

function getCounty(id){//擷取市對應的區
request = createRequest();
if (request == null) {
alert("Unable to create request");
return;
}
var url= "getDetails.php?ID=" + escape(id);
request.open("GET", url, true);
request.onreadystatechange = displayCounty;
request.send(null);
}


function displayProvince() {//將擷取的資料動態增加至select
if (request.readyState == 4) {
if (request.status == 200) {
var a=new Array;
var b=request.responseText;//將PHP返回的資料賦值給b
a=b.split(",");//通過","將這一資料儲存在數組a中
document.getElementById("sheng").length=1;
var obj=document.getElementById("sheng');
for(i=0;i
obj.options.add(new Option(a[i],i+1)); //動態產生OPTION加到select中,第一個參數為Text,第二個參數為Value值.

}
}
}


function displayCity() {//將擷取的資料動態增加至select
if (request.readyState == 4) {
if (request.status == 200) {
var a=new Array;
var b=request.responseText;
a=b.split(",");
document.getElementById("shi").length=1;//重新選擇
document.getElementById("xian").length=1;//重新選擇
if(document.getElementById("sheng").value!="province"){
var obj=document.getElementById('shi');
for(i=0;i
obj.options.add(new Option(a[i], document.getElementById("sheng").value*100+i+1)); //ocument.getElementById("sheng").value*100+i+1對應的是市的ID。
}

}
}
}

function displayCounty() {//將擷取的資料增加至select
if (request.readyState == 4) {
if (request.status == 200) {
var a=new Array;
var b=request.responseText;
a=b.split(",");
document.getElementById("xian").length=1;
if(document.getElementById("sheng").value!="province"&&document.getElementById("shi").value!="city"){
var obj=document.getElementById('xian');
for(i=0;i
obj.options.add(new Option(a[i],i+1001));
}

}
}
}

getDetails.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=root;Password=123456;Initial Catalog=area;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;
}
?>

資料庫設計,表格Province表,City表,County表。
要求:Province表需要id和name,id建議從1至34,例如北京id為1,廣東id為2,以此類推;
City表需要id,name和cid,id為cid*100+1,cid為該市的上級,例如深圳的上級為廣東省,cid為2的話,深圳的id就是201,以此類推。
County表需要id,name和cid,因為是三級的關係,id可以隨意,建議從10001開始自增。cid為所在上級,例如寶安區的cid為201,龍崗區的cid也為201;

HTML效果:

完成後效果:

備忘:PHP是伺服器端的,建議發布網站後通過ip調試。

http://www.bkjia.com/PHPjc/774993.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/774993.htmlTechArticle基本思想就是:在JS動態建立select控制項的option,通過Ajax擷取在PHP從SQL資料庫擷取的省市區資訊,代碼有點長,但很多都是類似的,例如JS中省...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.