Ajax achieves second-level urban linkage (I), and ajax achieves city Linkage
In the previous article, both provinces and cities are written in JS. Here, the city is put in PHP, And the Ajax request is sent to render the city data to the page.
1. html
<Select id = "province"> <option> select </option> <option> Shandong province </option> <option> Liaoning province </option> <option> Jilin province </option> </select> <select id = "city"> <option> select </option> </select>
2. javascript
<Script>/** what do you need to consider? ** When Will Ajax asynchronous requests be executed? ** When you select a specific province * // 1. bind the onchange event var provinceEle = document. getElementById ("province"); provinceEle. onchange = function () {// clear var city = document. getElementById ("city"); var opts = city. getElementsByTagName ("option"); for (var z = opts. length-1; z> 0; z --) {city. removeChild (opts [z]);} if (provinceEle. value! = "Select") {// 2. execute Ajax asynchronous request var xhr = getXhr (); xhr. open ("post", "06.php"); xhr. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded"); xhr. send ("province =" + provinceEle. value); xhr. onreadystatechange = function () {if (xhr. readyState = 4 & xhr. status = 200) {// receives data from the server. var data = xhr. responseText; // data is a string and is converted to an array var cities = data. split (","); for (var I = 0; I <cities. length; I ++) {var option = document. createElement ("option"); var textNode = document. createTextNode (cities [I]); option. appendChild (textNode); city. appendChild (option) ;}}}}; // defines the function getXhr () {var xhr = null for the XMLHttpRequest object of the ajax core object; if (window. XMLHttpRequest) {xhr = new XMLHttpRequest ();} else {xhr = new ActiveXObject ("Microsoft. XMLHttp ") ;}return xhr ;}</script>
3. 06.php
<? Php // data used to process the second-level Association of client requests // 1. receive province information sent by the client $ province =$ _ POST ['province ']; // 2. determine the current province information and provide different city information switch ($ province) {case 'shandong province ': echo 'qingdao, Jinan, Weihai, Rizhao, Dezhou'; 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;} // is the response string from the server?>
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.