PHP + Mysql + Ajax + JS achieve provincial/municipal level-3 linkage

Source: Internet
Author: User

The basic idea is: dynamically create the select control option in JS and obtain the province and city information obtained from the SQL database in PHP through Ajax. The code is a bit long, but many of them are similar, for example, the method for obtaining provinces, municipalities, and districts in JS is similar. Different select statements are executed using different parameters in PHP.

Index.html code:

Copy codeThe Code is as follows:
<! 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> provincial/municipal level-3 linkage </title>
<META http-equiv = Content-Type content = "text/html; charset = gb2312">
<Script src = "scripts/thumbnails. js" type = "text/javascript"> </script>
</Head>

<Body>

<Div id = "description">
<Select style = "width: 100px;" onchange = "sech (this. id)" id = "sheng">
<Option value = "province"> select a province </option>
</Select>
<Select onchange = "sech (this. id)" id = "shi">
<Option value = "city"> select city </option>
</Select>
<Select id = "xian">
<Option value = "county"> select a county or township </option>
</Select>
</Div>

</Div>
</Body>
</Html>

Thumbnails. js code:

Copy codeThe Code is as follows:
Window. onload = getProvince;

Function createRequest () {// objects required for PHP interaction with Ajax
Try {
Request = new XMLHttpRequest (); // create a new request object;
} 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) {// onchange event of select triggered when the province or city changes

Var aa = document. getElementById (id );
If (id = "sheng "){
GetCity (aa. value); // here, aa. value is the province id
}
If (id = "shi ")
{
GetCounty (aa. value); // here, aa. value is the city id
}

}

Function getProvince () {// obtain all provinces
Request = createRequest ();
If (request = null ){
Alert ("Unable to create request ");
Return;
}
Var url = "getDetails. php? ID = 0 "; // when ID = 0 is passed to PHP, it gets all provinces
Request. open ("GET", url, true );
Request. onreadystatechange = displayProvince; // sets the callback function.
Request. send (null); // send the request
}

Function getCity (id) {// obtain the city corresponding to the province
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) {// obtain the region of the city
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 () {// dynamically Add the obtained data to select
If (request. readyState = 4 ){
If (request. status = 200 ){
Var a = new Array;
Var B = request. responseText; // assign the data returned by PHP to B
A = B. split (","); // pass "," Save this data in array
Document. getElementById ("sheng"). length = 1;
Var obj = document. getElementById ("sheng ');
For (I = 0; I
Obj. options. add (new Option (a [I], I + 1); // dynamically generated OPTION is added to select. The first parameter is Text, and the second parameter is Value.

}
}
}

 
Function displayCity () {// dynamically Add the obtained data to 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; // reselect
Document. getElementById ("xian"). length = 1; // reselect
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 corresponds to the city ID.
}

}
}
}

Function displayCounty () {// Add the obtained data to 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 code:

Copy codeThe Code is as follows:
<? 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) {// obtain the province list
$ Conn-> Open ($ connstr); // create a database connection
$ Sqlstr = "select name from Province"; // you can specify a query string.
$ Rs = $ conn-> Execute ($ sqlstr); // query the result.
$ Num_cols = $ rs-> Fields-> Count (); // obtain the number of dataset Columns
$ 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) {// obtain the city list corresponding to the province
$ Conn-> Open ($ connstr); // create a database connection
$ Sqlstr = "select name from City where cid =". $ _ REQUEST ['id']; // you can specify a query string.
$ Rs = $ conn-> Execute ($ sqlstr); // query the result.
$ Num_cols = $ rs-> Fields-> Count (); // obtain the number of dataset Columns
$ 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) {// obtain the list of counties corresponding to the province and city
$ Conn-> Open ($ connstr); // create a database connection
$ Sqlstr = "select name from County where cid =". $ _ REQUEST ['id']; // you can specify a query string.
$ Rs = $ conn-> Execute ($ sqlstr); // query the result.
$ Num_cols = $ rs-> Fields-> Count (); // obtain the number of dataset Columns
$ 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;
}
?>

Database design, table Province, City, and County.
Requirement: the id and name are required for the Province table. The id ranges from 1 to 34. For example, Beijing id is 1, Guangdong id is 2, and so on;
The City table requires the id, name, and cid. The id is cid * 100 + 1, and the cid is the upper level of the City. For example, if the upper level of Shenzhen is Guangdong and the cid is 2, the id of Shenzhen is 201, and so on.
The County table requires IDs, names, and CIDS. Because they are three-level relationships, IDS can be customized. We recommend that you increase the value from 10001. Cid is the parent. For example, the cid in Baoan District is 201, and the cid in Longgang District is 201;

:

HTML effect:

Effect after completion:

Note: PHP is on the server side. It is recommended to debug the website via ip address after the website is published.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.