In the initial stage of primary school, if the knowledge points are incomplete and wrong, I hope you will give pointers!
One, the basic content
4. Differences from synchronous interaction
(1) Synchronous interaction: When the client sends a request to the server, it responds to the server. During this process, the user cannot do anything else (only wait);
*Comparative comparison of execution speed Slow, the response is a full html page.
(2) Asynchronous interaction
* The execution speed is relatively fast, and the response is part of the data.
Second, realize the asynchronous interaction steps of ajax
1. Create an XMLHttpRequest object
function getXhr(){ //declare the XMLHttpRequest object var xhr = null; //Create according to the different situations of the browser if(window.XMLHttpRequest){ //represents other browsers except IE xhr=new XMLHttpRequest(); }else{ //Indicates ie browser (version 8 and earlier) xhr=new ActiveXobject('Microsoft.XMLHttp'); } return xhr; }
This object is particularly important, it is recommended to remember!
2. Establish a connection with the server side * use the open(method, url) methodof the XMLHttpRequest object * method - set the type of the current request
*url - set the address of the current request
3. Send a request to the server * using the send (request parameter) methodof the XMLHttpRequest object
*Format of request parameters - key=value
4. Receive the response data from the server (1) Use the onreadystatechangeevent of the XMLHttpRequest object to monitor the communication state of the server.
(2) Use the readyState property of the XMLHttpRequest object to determine the current state of the server (0-4).
*0 - (server side) not yet initialized
*1 - (server side) receiving
*2——(Server side) Receiving completed
*3——(server side) is responding
*4——(server side) response completed (3) Use the status
attribute of the XMLHttpRequest object to determine the status code (200) of the server side.
(4) Use the responseText property of the XMLHttpRequest object to receive the response data from the server.
Note : The method parameters in the above 2 are get and post. The two request types are different, and the writing methods are also different .
**GET request method:*send() methods do not work, but cannot be ignored! xhr.send(null);
*Request parameters - add to URL? key=value;
*get request type case:
html page code:
<!DOCTYPE html> <html> <head> <title>Achieving Ajax Asynchronous Interaction</title> <meta charset="utf-8" /> </head> <body> <input type="button" value="异步请求" id="btn"> <script> // Steps to implement Ajax asynchronous interaction var btn = document.getElementById("btn"); btn.onclick = function(){ /* * 1. The realization of Ajax mainly relies on the XMLHttpRequest object * * Create XMLHttpRequest object */ var xhr = getXhr (); /* * 2. Establish a connection with the server */ xhr.open("get","01.php?user=zhangwuji"); /* * 3. The client sends a request to the server */ xhr.send(null); /* * 4. The client receives the response from the server */ xhr.onreadystatechange = function(){ // Ensure that the server-side response data is sent if(xhr.readyState == 4){ // Make sure this request must be successful if(xhr.status == 200){ // Receive data from the server var data = xhr.responseText; // test console.log(data); } } } } // Define the function to create the XMLHttpRequest object function getXhr(){ // Declare the XMLHttpRequest object var xhr = null; // Create according to different browsers if(window.XMLHttpRequest){ // other browsers xhr = new XMLHttpRequest(); }else{ // IE browser (8 and before) xhr = new ActiveXObject("Microsoft.XMLHttp"); } // return XMLHttpRequest object return xhr; } </script> </body> </html>
php page code:
<?php // Used to handle client-side Ajax asynchronous requests // 1. Receive the request data sent by the client $user = $_GET['user']; // 2. Respond to the client echo $user.' get request succesful.'; ?>
**POST request method:
* Before the send method is called, use the setRequestHeader() method to set the request header information
固定写法:xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
POST method request case:
html page code:<!DOCTYPE html> <html> <head> <title>Ajax by POST</title> <meta charset="utf-8" /> </head> <body> <input type="button" value="异步" id="btn"> <script> var btn = document.getElementById("btn"); btn.onclick = function(){ // Implement Ajax asynchronous interaction var xhr = getXhr (); xhr.open("post","02.php"); /* * If Ajax is using POST request type * * Must be called before send() method * * Use the setRequestHeader(key,value) method * * This method is used to set the request header */ xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xhr.send("user=zhangwuji"); xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 200){ var data = xhr.responseText; console.log(data); } } } } function getXhr(){ var xhr = null; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject("Microsoft.XMLhttp"); } return xhr; } </script> </body> </html>
php page code:
<?php // 1. Receive the request sent by the client $user = $_POST['user']; // 2. Respond echo $user.' post request successful.'; ?>
Comprehensive case: Using ajax to achieve secondary linkage of provinces, cities and districts
html code:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Secondary linkage full ajax implementation</title> </head> <body> <select id="shengji"> <option>-Please select-</option> </select> <select id="city"> <option>-Please select-</option> </select> <script> function getXhr(){ var xhr = null; if(window.XMLHttpRequest){ xhr=new XMLHttpRequest(); } else{ xhr=new ActiveXObject("Microsoft.XMLHttp"); } return xhr; }//Create XMLHttpRequest object var xhr = getXhr (); var shengji=document.getElementById("shengji"); var city=document.getElementById("city"); window.onload=function(){//The page is loaded and executed xhr.open("get","ajaxejld2.php?status=1"); xhr.send(null); xhr.onreadystatechange=function(){ if(xhr.readyState==4&&xhr.status==200){ var data=xhr.responseText; var province=data.split(","); for(var i=0;i<province.length;i++){ var option=document.createElement("option"); option.innerHTML=province[i]; shengji.appendChild(option); } } } } shengji.onchange=function(){//Execute when the first selection changes var opts=city.getElementsByTagName("option"); for(var j=opts.length-1;j>0;j--){ city.removeChild(opts[j]);//First clear the second select element } if(shengji.value!="-Please choose-"){ xhr.open("post","ajaxejld2.php"); xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xhr.send("status=2&province="+shengji.value); xhr.onreadystatechange=function(){ if(xhr.readyState==4&&xhr.status==200){ var data=xhr.responseText; var citys=data.split(","); for(var i=0;i<citys.length;i++){ var option=document.createElement("option"); option.innerHTML=citys[i]; city.appendChild(option); } } } } } </script> </body> </html>
php page code:
<?php $status=$_REQUEST['status']; if($status==1){ echo 'Chongqing City, Beijing City, Tianjin City, Hebei Province'; }else{ $province=$_POST['province']; switch($province){ case 'Chongqing City': echo 'Yuzhong District, Yubei District, Shapingba District, Jiulongpo District, Liangjiang New District, Beibei District'; break; case 'Beijing': echo 'Dongcheng District, Xicheng District, Haidian District, Chaoyang District'; break; case 'Tianjin': echo 'Hedong District, Hexi District, Nankai District'; break; case 'Hebei Province': echo 'Shijiazhuang City, Langfang City, Baoding City, Tangshan City, Qinhuangdao City'; break; } } ?>Note: The format of the data in the above is HTML (text format), and the ajax data format also includes XML, json; this is only the operation of native js, you can also use jquery to operate to make it easier, and continue to write later. Click to open the link