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
Dynamically switch Laravel 8 database connections according to URL parametersDynamically switch Laravel 8 database connections according to URL parametersAug 08, 2025 pm 04:36 PM

This article describes how to dynamically switch database connections according to URL parameters in Laravel 8 applications to avoid defining a large number of database connection configurations in .env files. Flexible database selection is achieved by modifying database configuration and clearing connections at runtime.

Taming Nested Structures: A Guide to `array_walk_recursive`Taming Nested Structures: A Guide to `array_walk_recursive`Aug 08, 2025 pm 04:34 PM

array_walk_recursive() is a powerful function in PHP for processing nested arrays. It can recursively apply callback functions to each leaf node value in a multidimensional array. 1. It accepts arrays and callback functions as necessary parameters, and can choose the third parameter to pass additional data; 2. It only acts on non-array elements, suitable for deep data processing such as string cleaning and type conversion; 3. It is often used for input filtering, data standardization and encoding conversion; 4. Limitations include the inability to modify key names, not traverse objects, directly modifying the original array, and being unable to process container structure; 5. If more refined control is required, custom recursive functions such as deep_map() should be used. Therefore, when only leaf nodes need to be processed and modifications are allowed in-place, array_wal

Dynamically switch Laravel 8 database connections according to URL parametersDynamically switch Laravel 8 database connections according to URL parametersAug 08, 2025 pm 04:27 PM

This article introduces how to dynamically switch database connections according to URL parameters in Laravel 8 project. By modifying configuration information and clearing connections, you can connect to different MySQL databases at runtime without predefined large database connection configurations.

Dynamic Switching Laravel 8 Database Connection: Based on URL ParametersDynamic Switching Laravel 8 Database Connection: Based on URL ParametersAug 08, 2025 pm 04:15 PM

This article describes how to dynamically switch database connections based on URL parameters in a Laravel 8 application. By modifying the configuration information and clearing the connection cache, you can connect to different databases at runtime, avoiding defining a large number of connection configurations in the .env file. This is very useful for application scenarios where multiple databases need to be accessed and the database names have a certain regularity.

Magento 2: Add custom buttons and functions to the order details pageMagento 2: Add custom buttons and functions to the order details pageAug 08, 2025 pm 04:06 PM

This document details how to add a custom button to the order details page of the Magento 2 backend and perform the custom function after clicking the button. We will create a simple module that will add a "Do Something" button to the order viewing page. Clicking it will trigger a controller that can perform any action you want, such as updating order status, sending emails, etc. This document will provide complete code examples and configuration instructions to help you implement this feature quickly.

Magento 2: Add custom buttons and implement functions on the order details pageMagento 2: Add custom buttons and implement functions on the order details pageAug 08, 2025 pm 03:57 PM

This document details how to add a custom button to the order details page of the Magento 2 backend and configure its clicked functionality. By creating custom modules, configuring routes, controllers, and plug-ins, you can implement custom button additions and functions, and provide complete code examples and configuration steps.

Magento 2: Add custom function buttons to the order details pageMagento 2: Add custom function buttons to the order details pageAug 08, 2025 pm 03:45 PM

This document details how to add a custom button to the order details page of the Magento 2 backend and enable a specific function to trigger after clicking. Through this article, you will learn how to create modules, configure routing, write controllers and plug-ins, and ultimately implement the functionality of custom buttons. At the same time, this article also considers the situation of enabling "Add Secret Key to URLs" to provide a more comprehensive solution.

Magento 2: Add custom buttons and function implementation to the order details pageMagento 2: Add custom buttons and function implementation to the order details pageAug 08, 2025 pm 03:36 PM

This document is intended to guide developers on how to add a custom button to the backend order details page of Magento 2 and execute specific business logic after clicking that button. We will introduce in detail the creation, configuration, controller writing and plug-in use of modules to ensure that the button function is functioning properly and is compatible with URL security keys.

See all articles

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.