Home >Backend Development >PHP Tutorial >Province and city linkage function realized by PHP+ajax
This article mainly introduces the province and city linkage function implemented by PHP's original ajax. It analyzes in detail the principle and implementation method of ajax interaction, as well as the relevant operating skills for PHP combined with ajax to realize the province and city linkage drop-down menu function. What is needed Friends can refer to
for details:
The core of Ajax is the JavaScript object XmlHttpRequest. This object was first introduced in Internet Explorer 5 and is a technology that supports asynchronous requests. In short, XmlHttpRequest allows you to use JavaScript to make requests to the server and handle the responses without blocking the user.
XMLHttpRequest
The XMLHttpRequest object is implemented in most browsers and has a simple interface that allows data to be passed from the client to the server. , but it will not interrupt the user's current operation. The data transmitted using XMLHttpRequest can be in any format, although the name suggests data in XML format.
Developers should already be familiar with many other XML-related technologies. XPath can access data in XML documents, but understanding the XML DOM is required. Similarly, XSLT is the simplest and fastest way to generate HTML or XML from XML data. Many developers are already familiar with Xpath and XSLT, so it makes sense for AJAX to choose XML as the data exchange format. XSLT can be used on both the client and server sides, and it can reduce a large amount of application logic written in JavaScript.
For Internet Explorer:
Internet 5.0-6.0:
xmlhttp_request = new ActiveXObject("Msxml2.XMLHTTP.3.0"); //3.0或4.0,5.0 xmlhttp_request = new ActiveXObject("Msxml2.XMLHTTP"); xmlhttp_request = new ActiveXObject("Microsoft.XMLHTTP");
Internet 7.0 and above:
##
xmlhttp_request = new XMLHttpRequest();
var xmlhttp; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
try { if (window.ActiveXObject) { for (var i = 5; i; i--) { try { if (i == 2) { xmlhttp_request = new ActiveXObject("Microsoft.XMLHTTP"); } else { xmlhttp_request = new ActiveXObject("Msxml2.XMLHTTP." + i + ".0"); xmlhttp_request.setRequestHeader("Content-Type", "text/xml"); xmlhttp_request.setRequestHeader("Charset", "gb2312"); } break; } catch(e) { xmlhttp_request = false; } } } else if (window.XMLHttpRequest) { xmlhttp_request = new XMLHttpRequest(); if (xmlhttp_request.overrideMimeType) { xmlhttp_request.overrideMimeType('text/xml'); } } } catch(e) { xmlhttp_request = false; }
Send a request
You can call the open() and send() of the HTTP request class ) method, as shown below:xmlhttp_request.open('GET',URL,true); xmlhttp_request.send(null);
First parameter# of open()
## is the HTTP request method—GET, POST, or whatever the server supports that you want to call. According to the HTTP specification, this parameter must be capitalized; otherwise, some browsers (such as Firefox) may not be able to process the request.
is the URL of the requested page.
The third parameterSets whether the request is in asynchronous mode. If TRUE, the JavaScript function will continue execution without waiting for a response from the server. This is the "A" in "AJAX".
Server's responseThis needs to tell the HTTP request object which JavaScript function to use to process this response. The object's onreadystatechange property can be set to the function name of the JavaScript to be used, as follows:
xmlhttp_request.onreadystatechange =FunctionName;
FunctionName is created in JavaScript Be careful not to write the function name as FunctionName(). Of course, we can also create the JavaScript code directly after onreadystatechange, for example:
xmlhttp_request.onreadystatechange = function(){ // JavaScript代码段 };
First check the status of the request. Only when a complete server response has been received can the function handle the response. XMLHttpRequest provides the readyState attribute to judge the server response. The values of
readyState are as follows: 0 (Not initialized)
1 (Loading)2 (Loading completed )
3 (Interaction)
4 (Complete)
So only when readyState=4, a complete server response has been received, and the function can process the response. The specific code is as follows:
if (http_request.readyState == 4) { // 收到完整的服务器响应 }else { // 没有收到完整的服务器响应 }
When readyState=4, a complete server response has been received, and then the function will check the HTTP The status value of the server response. The complete status value can be found in the W3C document. When the HTTP server response value is 200, it indicates that the status is normal.
Processing data obtained from the serverThere are two ways to obtain these data:
(1) As text Return the server's response in the form of a string
(2) Return the response in the form of an XMLDocument object
Application architecture Application framework
(Small example 1)------- --demo5.php--get value passing method
<?php header("content-type:text/html;charset=utf-8"); ?> <html> <head> <title>事件</title> </head> <body> <form action="#" method="post"> 用户名<input type="text" value="" name="uname" id="uname"/> <span id="msg" style="color:red;"></span><br /> 密码<input type="password" value="" name="upwd" id="upwd"/> <br /> <input type="submit" value="注册"/> <br /> </form> <script type="text/javascript"> function $(id){ return document.getElementById(id); } //全局对象 var http = null; var uname = $("uname"); uname.onblur = function(){ //1:创建对象 xmlhttprequest 对象 if(window.XMLHttpRequest){ // FF GOOLE IE 8 9 10 http = new XMLHttpRequest(); }else{ //IE 6 7 http = new ActiveXObject("Micrsoft.XMLHTTP"); } //2:准备url地址与参数 ?? bug var url = "demo51_do.php?uname="+$("uname").value; //3:定义处理返回结果方法 http.onreadystatechange = result; //4:发送请求 http.open('GET',url,true);//异步 http.send(null); }; //5:接收服务器返回结果 function result(){ //6:判断状态 接收完成 0 初始 1 发送 2处理 3 发送结果 //4:发送结果结束 //404 not found //200 ok 正确响就能 //7:判断状态 数据正确 if(http.readyState == 4 && http.status == 200){ //8:接收返回结果 {text/xml} var rs = http.responseText; //9:显示结果 var ms = ""; if(rs == 1){ ms = "己存在"; }else{ ms = "可以使用"; } $("msg").innerHTML = ms; } } </script> </body> </html>
##demo51_do.php
<?php header("content-type:text/html;charset=utf-8"); $uname = $_GET['uname']; $link = mysql_connect("127.0.0.1","root",""); mysql_query("set names utf8"); mysql_select_db("test"); $sql = "select count(*) from t_user where name = '{$uname}'"; $rs = mysql_query($sql); if($row = mysql_fetch_array($rs)){ if($row[0] == 1){ echo "1";//己存在 }else{ echo "0";//不存在可以使用 } } mysql_free_result($rs); mysql_close($link); ?>
(Small example 2)
<?php header("content-type:text/html;charset=utf-8"); ?> <html> <head> <title>事件</title> </head> <body> <form action="#" method="post"> 用户名<input type="text" value="" name="uname" id="uname"/> <span id="msg" style="color:red;"></span><br /> 密码<input type="password" value="" name="upwd" id="upwd"/> <br /> <input type="submit" value="注册"/> <br /> </form> <script type="text/javascript"> function $(id){ return document.getElementById(id); } var http = null; var uname = $("uname"); uname.onblur = function(){ //1:创建对象 xmlhttprequest 对象 if(window.XMLHttpRequest){ http = new XMLHttpRequest(); }else{ http = new ActiveXObject("Microsoft.XMLHTTP"); } //2:准备url地址与参数 var url = "demo6_do.php"; //3:定义处理返回结果方法 http.onreadystatechange = result; //4:发送请求 http.open('POST',url,true); http.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); http.send("uname="+$("uname").value); }; //5:接收服务器返回结果 function result(){ //6:判断状态 接收完成 //7:判断状态 数据正确 if(http.readyState == 4 && http.status == 200){ //8:接收返回结果 {text/xml} var rs = http.responseText; var ms = ""; if(rs == 1){ ms = "己存在"; }else{ ms = "可以使用"; } //9:显示结果 $("msg").innerHTML = ms; } } </script> </body> </html>
demo6_do.php
<?php header("content-type:text/html;charset=utf-8"); $uname = $_POST['uname']; $link = mysql_connect("127.0.0.1","root",""); mysql_query("set names utf8"); mysql_select_db("test"); $sql = "select count(*) from t_user where name = '{$uname}'"; $rs = mysql_query($sql); if($row = mysql_fetch_array($rs)){ if($row[0] == 1){ echo "1";//己存在 }else{ echo "0";//不存在可以使用 } } mysql_free_result($rs); mysql_close($link); ?>
(Small example three)----xml
<?php header("content-type:text/html;charset=utf-8"); ?> <html> <head> <title>事件</title> </head> <body> <form action="#"> 省 <select name="sel" id="sel"> <option value='0'>--请选择--</option> <option value='1'>--河北--</option> <option value='2'>--河南--</option> <option value='3'>--广东--</option> </select> 市 <select name="city" id="city"> <option value='0'>--请选择--</option> </select> </form> <script type="text/javascript"> function $(id){ return document.getElementById(id); } var http = null; var sel = $("sel"); sel.onchange = function(){ //1:创建对象 xmlhttprequest 对象 if(window.XMLHttpRequest){ http = new XMLHttpRequest(); }else{ http = new ActiveXObject("Microsoft.XMLHTTP"); } //2:准备url地址与参数 var url = "demo7_do.php?shen="+$("sel").value; //3:定义处理返回结果方法 http.onreadystatechange = result; //4:发送请求 http.open('GET',url,true); http.send(null); }; //5:接收服务器返回结果 function result(){ //6:判断状态 接收完成 //7:判断状态 数据正确 if(http.readyState == 4 && http.status == 200){ //8:接收返回结果 {text/xml} var rs = http.responseXML; var citys = rs.getElementsByTagName("city"); for(var i = 0;i < citys.length;i++){ var o = document.createElement("option"); o.value = ""+(i+1); o.text = citys[i].firstChild.data; $("city").add(o,null); } //9:显示结果 } } </script> </body> </html>
demo7_do.php
<?php header("content-type:text/xml;charset=utf-8"); $shen = $_GET['shen']; if($shen == "1"){ $city = "<root><city>石家庄</city><city>保定</city><city>沧州</city></root>"; }else if($shen == "2"){ $city = "<root><city>郑州</city><city>新乡</city><city>登封</city></root>"; }else if($shen == "3"){ $city = "<root><city>东莞</city><city>中山</city><city>广州</city></root>"; } echo $city; ?>
Related recommendations :
) source code_PHP tutorial
ajax-ecshop Mobile terminalprovince and city linkagebug
The above is the detailed content of Province and city linkage function realized by PHP+ajax. For more information, please follow other related articles on the PHP Chinese website!