search
HomeBackend DevelopmentPHP TutorialProvince and city linkage function realized by PHP+ajax

Province and city linkage function realized by PHP+ajax

May 18, 2018 pm 02:37 PM
phpphp+ajaxFunction

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();


Automatically determined code:


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");
}


In practical applications, in order to be compatible with multiple different versions of browsers, the method of creating the XMLHttpRequest class is generally written in the following form:


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.

The second parameter

is the URL of the requested page.

The third parameter

Sets 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(&#39;GET&#39;,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[&#39;uname&#39;];
$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 = &#39;{$uname}&#39;";
$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)

Post value passing method demo6.php

<?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(&#39;POST&#39;,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[&#39;uname&#39;];
$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 = &#39;{$uname}&#39;";
$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

demo7.php

<?php
header("content-type:text/html;charset=utf-8");
?>
<html>
 <head>
  <title>事件</title>
 </head>
 <body>
 <form action="#">
  省
  <select name="sel" id="sel">
    <option value=&#39;0&#39;>--请选择--</option>
    <option value=&#39;1&#39;>--河北--</option>
    <option value=&#39;2&#39;>--河南--</option>
    <option value=&#39;3&#39;>--广东--</option>
  </select>
  市
  <select name="city" id="city">
    <option value=&#39;0&#39;>--请选择--</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(&#39;GET&#39;,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[&#39;shen&#39;];
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 :

Ajax PHP non-refresh secondary linkage drop-down menu (

province and city linkage

) source code_PHP tutorial

Written with AjaxProvince and City Linkage, how to display the existing provinces and cities in the address when modifying

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools