First, let's explain what Ajax is.
In short, Ajax = Asynchronous JavaScript and XML is a technology used to create fast dynamic web pages.
It is not a programming language, but a specification.
The main function of AJAX is to exchange a small amount of data with the server in the background.
That is to say, AJAX can be used to implement asynchronous updates on webpages. The most common example is:
When you enter keywords in the Google search box, JavaScript will send these characters to the server, and the server will return a list of search recommendations.
This means that you can update a part of a webpage without reloading the entire webpage.
Let's look at a small case of helloworld.
The program contains a div and a button.
DIV is used to display information from the server. When a button is clicked, it calls the function named loadxmldoc:
Next, add a <SCRIPT> label to the head of the page. The tag contains the loadxmldoc () function:
Let's take a look at several important concepts in Ajax.
1. XMLHttpRequest
XMLHttpRequest is used to exchange data with the server in the background.
That is to say, you can update a part of a webpage without reloading the entire webpage.
The method for creating XMLHttpRequest is simple:
variable=new XMLHttpRequest();
However, IE6 does not support XMLHttpRequest, but activexobject. Therefore, we need to make a judgment:
var xmlhttp;if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safarixmlhttp=new XMLHttpRequest();}else{// code for IE6, IE5xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
2. send a request to the server
To send requests to the server, you can use the open () and send () Methods of the XMLHTTPRequest object:
Method
|
Description |
Open (Method,URL,Async) |
Specifies the request type, URL, and whether to asynchronously process the request.
- Method: Request type; get or post
- URL: File location on the server
- Async: True (asynchronous) or false (synchronous)
|
Send (String) |
Send the request to the server.
- String: Used only for post requests
|
There are two types of requests: Get and post.
The code for sending a GET request is as follows:
xmlhttp.open("GET","demo_get.asp",true);xmlhttp.send();
However, this may cause a problem and the result may be cached,
The solution is to use a unique ID:
xmlhttp.open("GET","demo_get.asp?t=" + Math.random(),true);xmlhttp.send();
If you want to use get to transmit information, you can directly modify it in the address bar:
xmlhttp.open("GET","demo_get2.asp?fname=Bill&lname=Gates",true);xmlhttp.send();
The code for sending a POST request is as follows:
xmlhttp.open("POST","demo_post.asp",true);xmlhttp.send();
To post data like an HTML form, you can use setRequestHeader () to add an HTTP header. Then specify the data to be sent in the send () method:
xmlhttp.open("POST","ajax_test.asp",true);xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");xmlhttp.send("fname=Bill&lname=Gates");
SetRequestHeader (Header,Value): Add an HTTP header to the request, whereHeader: Specifies the name of the header,Value: Specifies the value of the header.
The following explains the meaning of true in the third parameter.
If the XMLHTTPRequest object is used for Ajax, The async parameter of its open () method must be set to true:
xmlhttp.open("GET","ajax_test.asp",true);
Sending asynchronous requests is a huge improvement. Many tasks executed on the server are time-consuming. Through Ajax, JavaScript does not need to wait for the server's response, but rather: 1. Execute other scripts while waiting for the server's response; 2. process the response when the response is ready.
Whether the request is asynchronous is divided into the following two situations:
When async = true is used, specify the function to be executed when the response is in the ready state of the onreadystatechange event:
xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } }xmlhttp.open("GET","test1.txt",true);xmlhttp.send();
To use async = false, change the third parameter in the open () method to false:
Async = false is not recommended, but it is also possible for small requests.
Remember, JavaScript will not continue until the server is ready for response. If the server is busy or slow, the application will be suspended or stopped.
Note: When you use async = false, do not write the onreadystatechange function-put the code after the send () Statement:
xmlhttp.open("GET","test1.txt",false);xmlhttp.send();document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
3. Server Response
To obtain a response from the server, use the responsetext or responsexml attribute of the XMLHTTPRequest object.
- Responsetext: obtains response data in the string format.
If the response from the server is not XML, you can use the responsetext attribute.
The responsetext property returns a string-type response, so you can use:
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
- Responsexml: Get Response Data in XML format.
If the response from the server is XML and needs to be parsed as an XML object, use the responsexml attribute:
xmlDoc=xmlhttp.responseXML;txt="";x=xmlDoc.getElementsByTagName("ARTIST");for (i=0;i<x.length;i++) { txt=txt + x[i].childNodes[0].nodeValue + "<br />"; }document.getElementById("myDiv").innerHTML=txt;
4. onreadystatechange event
When a request is sent to the server, we need to execute some response-based tasks.
When the readystate changes, the onreadystatechange event is triggered.
The readystate attribute contains the status information of XMLHttpRequest.
The following are three important attributes of the XMLHTTPRequest object:
Attribute |
Description
|
Onreadystatechange |
A storage function (or function name) that is called whenever the readystate attribute changes. |
Readystate |
XMLHttpRequest status. Changes from 0 to 4.
- 0: the request is not initialized.
- 1: The server connection has been established.
- 2: The request has been received
- 3: The request is being processed
- 4: The request is complete and the response is ready.
|
Status
|
200: "OK" 404: Page not found |
In the onreadystatechange event, we specify the tasks executed when the server responds to the prepared tasks.
When readystate is 4 and the status is 200, the response is ready:
xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } }
5. Use the callback function
The callback function is a function that is passed to another function as a parameter.
If your website has multiple Ajax tasks, you should writeStandardAnd call this function for each Ajax task.
This function call should contain URLs and tasks executed when the onreadystatechange event occurs (each call may be different ):
function myFunction(){loadXMLDoc("ajax_info.txt",function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } });}