Table of Contents
Ajax PHP non-refresh secondary linkage drop-down menu (
Home Backend Development PHP Tutorial Province and city linkage function realized by PHP+ajax

Province and city linkage function realized by PHP+ajax

May 18, 2018 pm 02:37 PM
php php+ajax Function

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");
Copy after login


Internet 7.0 and above:


##

xmlhttp_request = new XMLHttpRequest();
Copy after login


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


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;
}
Copy after login


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);
Copy after login


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;
Copy after login


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代码段
};
Copy after login


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 {
// 没有收到完整的服务器响应
}
Copy after login


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>
Copy after login

##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);
?>
Copy after login


(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>
Copy after login


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);
?>
Copy after login


(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>
Copy after login


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;
?>
Copy after login

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 of this Website
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

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles