Deep understanding of Ajax in JavaScript
- 2021-07-07 06:11:48
- OfStack
Ajax is not a new programming language, but a new approach using existing standards. AJAX can exchange data with the server without reloading the entire page. This asynchronous interaction enables users to get new data without refreshing the page after clicking.
XMLHttpRequest object
The core of Ajax is the XMLHttpRequest object (XHR). XHR provides an interface for sending requests to the server and parsing server responses. Ability to retrieve new data from the server asynchronously.
Create an object in a browser (only IE 7 and later are supported):
var xhr = new XMLHttpRequest();
Usage of XHR
The first thing to introduce is the open () method. It accepts three parameters:
The type of request to send (POST, GET, etc.)
• Requested URL
A Boolean value indicating whether the request is sent asynchronously
Call the open () example:
xhr.open("get", "index.jsp", false);
GET request for index. jsp. URL relative to the current page on which the code is executing; Calling the open () method does not really send a request, just initiates a request for sending.
Call send () to send the request:
xhr.send(null);
send () receives one parameter, which is the data to be sent as the subject of the request. If you do not need to send data through the request principal, you must pass in null.
The corresponding data is populated into the related properties of the XHR object:
• ES 73EN: Text returned as response subject
• responseXML: The content type in response is "text/xml" or "application/xml"
• status: HTTP state of response
• statusText: Description of HTTP status
After receiving the response, first check the status property to determine that the response has returned, with 1 or 200 as a success flag. The status code 304 indicates that the resource has not been modified, and the version cached in the browser can be used directly.
In order to receive an appropriate response, two status codes should be detected as follows:
xhr.open("get", "index.jsp", false);
xhr.send(null);
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
alert(xhr.responseText);
} else {
alert("Request was unsuccessful: " + xhr.status);
}
By detecting the readyState attribute, you can determine the current active phase of the request/response process.
0: Not initialized. open () method not called
1: Start. The open () method has been called, and the send () method has not been called
2: Send. The send () method has been called and no response has been received
3: Receive. Partial data has been received
4: Done. All data has been received and can be used on the client
The readystatechange event is triggered once when the value of the readyState property changes. Specifying an onreadystatechange event handler before calling open () ensures browser compatibility.
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
alert(xhr.responseText);
} else {
alert(" Request successful: " + xhr.status);
}
}
};
xhr.open("get", "index.jsp", true);
xhr.send(null);
You can cancel the asynchronous request before receiving the response:
xhr.abort();
HTTP header information
XHR objects provide methods for manipulating request headers and response header information.
By default, the following header information is sent along with the XHR request.
• ES 150 EN: The type of content that the browser can handle
• Accept-Charset: Character set that browser can display
• ES 159EN-ES 160EN: Compression encoding that can be handled by browsers
• Accept-Language: The language currently set by the browser
• ES 169EN: Type of connection between browser and server
• Cookie: Any Cookie set up on the current page
• ES 178EN: Domain of the page from which the request was made
• ES 182EN: ES 183EN of the page from which the request was made
• User-Aent: User Agent String for Browser
Use setRequestHeader () to set custom request header information. You must call after calling the open () method and before calling send ()
setRequestHeader ():
xhr.open("get", "index.jsp", true);
xhr.setRequestHeader("MyHeader", "MyValue");
xhr.send(null);
Call getResponseHeader () and pass in the field name to get the corresponding response header information. getAllResponseHeader () gets a long string containing all header information.
var myHeader = xhr.getResponseHeader("MyHeader");
var allHeaders = xhr.getAllResponseHeader();
GET Request
GET is used to query the server for certain information. You can append query string parameters to the end of URL, and the name and value of each parameter in the query string must be encoded using encodeURIComponent ():
xhr.open("get", "login.jsp?name1=value1&name2=value2", false);
addURLParam() Receive 3 Parameters to add: the URL The name of the parameter and the value of the parameter.
var url = "login.jsp";
// Add parameters
url = addURLParam(url, "username", "xxyh");
url = addURLParam(url, "password", "xxyh123");
// Initialize request
xhr.open("get", url, false);
POST Request
The POST request is used to send data to the server that should be saved. The body of an POST request can contain very large amounts of data in any format.
Initialize the request:
xhr.open("post", "login.jsp", true);
First, the Content-Type The header information is set to application/x-www-form-urlencoded, Then establish 1 String format. If you need to serialize the form data in the page, and then pass the XHR To the server, you can use the serialize() Function to create this string:
xhr.open("get", "login.jsp", false);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
var form = document.getElementById("user-info");
xhr.send(serialize(form));