Ajax is not a new programming language, but a new approach that uses existing standards. AJAX can exchange data with the server without reloading the entire page. This asynchronous interaction method allows users to obtain new data without having to refresh 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 resolving server responses. Ability to obtain new data from the server in an asynchronous manner.
Create objects in the browser (only support IE7 and higher):
var xhr = new XMLHttpRequest();
How to use XHR
The first thing to introduce is the open() method. It receives 3 parameters:
•The type of request to be sent (POST, GET, etc.)
•Requested URL
•Bolean value indicating whether the request is sent asynchronously
Calling open() example:
xhr.open("get", "index.jsp", false);
GET request for index.jsp. The URL is relative to the current page where the code is executed; calling the open() method does not actually send the request, it just starts a request for sending.
Call send() to send the request:
xhr.send(null);
send() receives a parameter, that is, the data to be sent as the requesting body. If data is not required to be sent through the request body, null must be passed in.
The corresponding data will be filled with the relevant properties of the XHR object:
•responseText: The text returned as the response body
•responseXML: The content type as the response is "text/xml" or "application/xml"
•status: The HTTP status of the response
•statusText: Description of HTTP status
After receiving the response, first check the status attribute and confirm that the response has returned, generally 200 is used as a sign of success. The status code 304 indicates that the resource has not been modified and the cached version in the browser can be used directly.
In order to receive a suitable response, two status codes should be detected in the following manner:
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 property, the current active phase of the request/response process can be determined.
•0: Not initialized. The open() method was 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, no response was received
•3: Receive. Some data has been received
•4: Completed. All data has been received and can be used on the client side
When the value of the readyState property changes, a readystatechange event will be triggered. To ensure browser compatibility, specify the onreadystatechange event handler before calling open().
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);The asynchronous request can be cancelled before receiving the response:
xhr.abort();
HTTP header information
XHR objects provide methods for manipulating request headers and responding to header information.
By default, while sending an XHR request, the following header information will also be sent.
•Accept: The type of content that the browser can handle
•Accept-Charset: The character set that the browser can display
•Accept-Encoding: Compressed encoding that the browser can handle
•Accept-Language: The language currently set by the browser
•Connection: The type of connection between the browser and the server
•Cookie: Any cookies set on the current page
•Host: The domain where the page where the request was issued is located
•Referer: URL of the page that issued the request
•User-Aent: The browser's user agent string
Use setRequestHeader() to set custom request header information. You must call the open() method after calling it 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 the query string parameters to the end of the URL. 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() receives three parameters: the URL of the parameter to be added, the name of the parameter, and the value of the parameter. var url = "login.jsp";// Add parameter url = addURLParam(url, "username", "xxyh");url = addURLParam(url, "password", "xxyh123");// Initialize the 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 a POST request can contain a lot of data, and the format is unlimited.
Initialization request:
xhr.open("post", "login.jsp", true); First set the Content-Type header information to application/x-www-form-urlencoded, and then create a string format. If you need to serialize the form data in the page and then send it to the server through XHR, 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));The above is the in-depth understanding of Ajax in JavaScript introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!