An in-depth understanding of the XHR object in the first ajax series, ajaxxhr
Previous
Ajax is short for asynchronous javascript and XML, and Chinese translation is asynchronous javascript and XML. This technology can request additional data from the server without the need to uninstall the page, which will bring a better user experience. Although the name contains XML, ajax communication is irrelevant to the data format. The following describes ajax content in detail.
Create
The core of ajax technology is the XMLHttpRequest object (XHR), a feature first introduced by Microsoft. Other browser providers later provided the same implementation. XHR provides a smooth interface for sending requests to the server and parsing server responses. XHR can obtain more information from the server asynchronously, meaning that after you click it, you can obtain new data without refreshing the page.
IE5 is the first browser to introduce XHR objects. In IE5, XHR objects are implemented through an ActiveX object in the MSXML library, while IE7 + and other standard browsers support native XHR objects.
Create an XHR object or instantiate an XHR object because XMLHTTPRequest () is a constructor. The following is a compatible method for creating XHR objects
var xhr;if(window.XMLHttpRequest){ xhr = new XMLHttpRequest();}else{ xhr = new ActiveXObject('Microsoft.XMLHTTP');}
Send request
Open ()
When using an XHR object, the first method to be called is open (), which accepts three parameters: the type of the request to be sent ("get", "post", etc), the request URL and Boolean value indicating whether to send the request Asynchronously
xhr.open("get","example.php", false);
[Note] a URL is the current page relative to the code execution, and can only send requests to URLs that use the same port and protocol in the same domain. If the URL differs from the page on which the request is initiated, a security error is thrown.
Send ()
The send () method receives a parameter, that is, the data to be sent as the request body. After the send () method is called, the request is distributed to the server.
xhr.open("get", "example.txt", false);xhr.send(null);
Receive response
After receiving the response, the response data will automatically fill in the XHR object attributes, mainly including the following four attributes:
ResponseText: Text returned as the response body
ResponseXML: If the response content type is 'text/xml' or 'application/xml', this attribute stores the xml DOM document for the response data.
Status: the HTTP status of the response.
StatusText: HTTP status description
After receiving the response, the first step is to check the status attribute to confirm that the response has been returned successfully. Generally, the HTTP Status Code 200 can be used as a sign of success. At this point, the content of the responseText attribute is ready, and the responseXML can be accessed when the content type is correct. In addition, the status code 304 indicates that the requested resource has not been modified. You can directly use the cached version in the browser. Of course, it also means that the response is effective.
Regardless of the content type, the content of the response body is saved to the responseText attribute. For non-XML data, the value of the responseXML attribute is null.
if((xhr.status >=200 && xhr.status < 300) || xhr.status == 304){ alert(xhr.responseText);}else{ alert('request was unsuccessful:' + xhr.status);}
Asynchronous
If you want to receive an asynchronous response, you need to check the readyState attribute of the XHR object. This attribute indicates the current active phase of the Request/response process. The optional values of this attribute are as follows:
0 (UNSENT): not initialized. The open () method has not been called.
1 (OPENED): Start. The open () method has been called, but the send () method has not been called.
2 (HEADERS_RECEIVED): Send. The send () method has been called and received to the header.
3 (LOADING): receive. Some response body information has been received
4 (DONE): complete. All response data has been received and can be used on the client.
A readystatechange event is triggered as long as the value of readyState changes from one value to another. This event can be used to detect the value of readyState after each state change. Generally, we are interested in the stage with the readyState value 4, because all data is ready.
[Note] You must specify the onreadystatechange event handler before calling open () to ensure cross-browser compatibility. Otherwise, the readyState attribute 0 and 1 cannot be received.
xhr.onreadystatechange = function(){ if(xhr.readyState === 4){ if(xhr.status == 200){ alert(xhr.responseText); } }}
Instance
The following uses a small example to demonstrate the xhr object application in ajax.
<Button id = "btn"> obtain information </button> <div id = "result"> </div> <script> btn. onclick = function () {// create xhr object var xhr; if (window. XMLHttpRequest) {xhr = new XMLHttpRequest ();} else {xhr = new ActiveXObject ('Microsoft. XMLHTTP ');} // asynchronously accepts the response xhr. onreadystatechange = function () {if (xhr. readyState = 4) {if (xhr. status = 200) {// actual operation result. innerHTML + = xhr. responseText ;}}// send the request xhr. open ('get', 'message. xml ', true); xhr. send () ;}</script>
// Message. xml
<p>hello world</p>
Last
The demo shows that the content of the ajax front-end is not difficult. However, ajax is not easy to learn because it involves some backend and network knowledge. In the future, we will gradually introduce the key content of ajax.
The above is the XHR object described in the first article in the ajax series by the editor. I hope it will help you!