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 :
Ajax PHP non-refresh secondary linkage drop-down menu (
province and city linkage) 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!
Hot AI Tools
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undress AI Tool
Undress images for free
Clothoff.io
AI clothes remover
AI Hentai Generator
Generate AI Hentai for free.
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
1377
52
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
Discuss CakePHP
Sep 10, 2024 pm 05:28 PM
CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu
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?
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
CakePHP Quick Guide
Sep 10, 2024 pm 05:27 PM
CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.
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 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,
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


