Ajax achieves second-level urban linkage (3) and ajax achieves city Linkage
The example in this article shares the code for Ajax to implement second-level urban linkage for your reference. The details are as follows:
This is the third article in the Ajax second-level urban linkage series, integrating the previous two articles
1. html
<Select id = "province"> <option> select </option> </select> <select id = "city"> <option> select </option>/ select>
2. javascript
// Create the function getXhr () {var xhr = null; if (window. XMLHttpRequest) {xhr = new XMLHttpRequest ();} else {xhr = new ActiveXObject ("Microsoft. XMLHttp ") ;}return xhr;} var xhr = getXhr (); // the first time an Ajax asynchronous request is executed-the provincial window. onload = function () {xhr. open ("get", "finaly. php? State = 1 "); xhr. send (null); xhr. onreadystatechange = function () {if (xhr. readyState = 4 & xhr. status = 200) {var data = xhr. responseText; // converts a string to an array var provinces = data. split (","); // traverse the array for (var I = 0; I <provinces. length; I ++) {// create the option element and add it to the var option = document. createElement ("option"); var text = document. createTextNode (provinces [I]); option. appendChild (text); var province = document. GetElementById ("province"); province. appendChild (option) ;}}}; // The second Ajax asynchronous request-city var province = document. getElementById ("province"); province. onchange = function () {var city = document. getElementById ("city"); var opts = city. getElementsByTagName ("option"); for (var z = opts. length-1; z> 0; z --) {city. removeChild (opts [z]);} if (province. value! = "Select") {xhr. open ("post", "finaly. php "); xhr. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded"); xhr. send ("state = 2 & province =" + province. value); xhr. onreadystatechange = function () {if (xhr. readyState = 4 & xhr. status = 200) {var data = xhr. responseText; var cities = data. split (","); for (var I = 0; I <cities. length; I ++) {var option = document. createElement ("option"); var text = document. createTextNode (cities [I]); option. appendChild (text); city. appendChild (option );}}}}};
3. finaly. php
<? Php // receives the REQUEST data sent by the client-state $ state =_ _ REQUEST ['state']; // determines the value of $ state if ($ state = 1) {// obtain the province echo 'shandong province, Liaoning province, Jilin province ';} else {// obtain the city $ province =$ _ POST ['province']; switch ($ province) {case 'shandong province ': echo 'qingdao city, Jinan City, Weihai City, Rizhao City, Dezhou City'; break; case 'liaoning province ': echo 'shenyang city, Dalian city, Tieling City, Dandong City, Jinzhou City '; break; case 'Jilin province ': echo 'changchun city, Songyuan City, Jilin City, Tonghua City, Siping City'; break ;}}?>
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.