The beauty of JavaScript Ajax
There was a period of time, because the developer of the misuse of JavaScript led to a period of unpopular times, not be optimistic, and then, to 2005 years, Google's many technologies are used Ajax, JavaScript is again hot up, can say, Ajax has saved JavaScript, and for now, being proficient in using Ajax has become a skill that all Web developers have to master. So what about Ajax? What is the role of it?
The first part: Introduction to Ajax
Ajax is shorthand for asynchronous JavaScript +xml, a technique that can request additional data from the server without uninstalling the page, resulting in a better user experience. The core of Ajax is the XMLHttpRequest object (referred to as XHR, which is supported by mainstream browsers such as Chrome, Safari, FF, opera, etc.), a feature introduced by Microsoft First, IE uses ActiveXObject, The same implementation was later provided by the browser provider. the existence of the XHR object means that when the user clicks it, it is possible to get new data from the background without having to refresh the page, that is, you can try the Xhr object to get new data, and then insert the new data into the page in the DOM way to update the part of the page. It is worth noting that although Ajax contains XML, the data we get without having to refresh the page is not necessarily XML data.
Part II: Creation of XHR objects
As mentioned above, the core of Ajax is the XMLHttpRequest object, so how do we create a XMLHttpRequest object?
First, we should know that all browsers support XMLHttpRequest objects, where IE5 and IE6 use ActiveXObject objects. And now all browsers (ie7+, FireFox, Chrome, Safari, and Opera) have built-in XMLHttpRequest objects. So the syntax for creating XMLHttpRequest objects is:
var xhr = new XMLHttpRequest ();
Just mentioned that older versions of Internet Explorer (IE5 and IE6) use ActiveXObject objects, so the syntax is:
var Axo = new ActiveXObject ("Microsoft.XMLHTTP");
Note: The incoming "microsoft.xmlhttp" cannot be changed.
Therefore, in order to deal with all modern browsers (including IE5 and IE6), first check whether the XMLHttpRequest object is supported: Create a XMLHttpRequest object if supported, or create a ActiveXObject object if it is not supported:
var xmlhttp=null;if (window. XMLHttpRequest) { xmlhttp=new XMLHttpRequest ();} else{ xlmhttp=new ActiveXObject ("Microsoft.XMLHTTP");}
The code for this response to all modern browsers should be noted:
- I set the value of XMLHTTP to NULL because a null value represents an empty object pointer, and that is why using the TypeOf operator to detect that a null value returns "Object", so: if the defined variable is intended to be used for saving the object in the future, It is better to initialize the variable to null instead of the other value.
- You can try window. XMLHttpRequest to detect if it exists because XMLHttpRequest is a property of the Window object.
Part III: Usage of XHR objects (properties and methods, etc.)
In the above two sections, we describe what the XHR object is and how to create it, and this Part I will talk about the usage of the XHR object.
⑴.open () method
Since XHR is an object, it must have its own properties and methods. When using a Xhr object, the first method to invoke is open (). It accepts 3 parameters:
- The type of request to send: Get, post, put, delete, and so on.
- The requested URL (this URL can be either an absolute or a relative path).
- The Boolean value of whether to send the request asynchronously: TRUE indicates that the request was sent asynchronously, and false indicates that the request was sent synchronously.
Examples are as follows:
Xhr.open ("Get", "example.php", true);
At this point, the code initiates a GET request for example.php. Note: The Open () method does not actually send the request but only initiates a request for sending. so how to send a specific request, this is the use of the Send () method.
⑵.Send () method
Just talking about the open () method, just open, not yet sent, and send is really sent. It takes a parameter:
- Data sent as the request Principal
Note: If you do not need to send data through the request principal, you must pass in NULL. A generic GET request does not require an incoming parameter, and for a POST request, if you need to post data like an HTML form, use setRequestHeader () to add an HTTP header. Then specify the data you want to send in the Send () method. This section will be described in detail, here is a simple example:
Xhr.open ("Get", "example.php", true); Xhr.send (null);
(3). Several properties of the Xhr object
When sent through send (), the response is accepted and the response data is automatically populated with the properties of the Xhr object. There are mainly the following types:
- ResponseText: Text returned as the response body
- Responsexml: If the content type of the response is "text/xml" or "application/xml", this property will hold the XML DOM document containing the corresponding data.
- Status: HTTP status of the response
- Description of the Statustext:http status
When a response is received, the Status property is typically checked to determine if the response returned successfully, and a general status code of 200 indicates success (which starts with 2), which is responsetext to be accessed. A status code of 304 indicates that the requested resource has not been modified and can be used directly from the cached version in the browser, so this response is also valid. You can then detect the two states by using the following code:
Xhr.open ("Get", "example.php", false); Xhr.send (null); if (xhr.status>=200&&xhr.status<300) | | xhr.status==304) {alert (xhr.responsetext);} Else{alert ("Request waw unseccessful:" + "Xhr.status");}
The ReadyState property of the Xhr object
Using Ajax we would of course want to send an asynchronous request: If a sync request is sent, then once the NIC is in, the page will not react but continue to wait for the response, but send an asynchronous request, even if the NIC is live, without worrying because it is asynchronous. the ReadyState property can detect the current active phase of the request/response process . It has 5 values, respectively, as follows:
Key: as long as the value of the readystate changes (for example, from 0 to 1, from 1 to 2, etc.), the ReadyStateChange event is triggered every time the change occurs. And it is possible to detect the value of the readystate after each state change by this time. The value of 4 is the most important because all the data is ready. See an example:
var xhr=new xmlhttprequest (); Xhr.open ("Get", "example.php", false); Xhr.onreadystatechange=function () {if (readystate ==4) {if (xhr.status>=200&&xhr.status<300) | | | xhr.status==304) {alert (xhr.responsetext);} Else{alert ("Request waw unseccessful:" + "Xhr.status");}}; Xhr.send (NULL);
Note the following points:
- Xhr.onreadystatechange is preceded by an on, because we are using the DOM0-level method to add a time handler for the Xhr object, without using the DOM2-level method of AddEventListener, is because not all browsers support the DOM2-level approach .
- In this example, we are not using this object because of the scope problem of the onreadystatechange time handler. If you use the This object, in some browsers it can cause the function to fail or cause an error to occur. Therefore, it is a more reliable way to use actual instances of XHR objects to facilitate that.
(4). Abort () method
Before accepting the response, we can also use the Abort () method to cancel the asynchronous request as follows:
Xhr.abort ();
After this method is called, the XHR object stops triggering the event and no longer allows access to any object properties related to the response.
Part IV: HTTP header information
Because the use of Ajax and background interaction, then must be inseparable from the HTTP protocol. The HTTP request and response will have the appropriate header information.
By default, the following header information is also sent at the same time that the XHR request is sent.
- Accept: Content types that the browser can handle
- Accept-charset: The character set that the browser can display
- Accept-encodding: Compression encoding that the browser can handle
- Accept-language: The language currently set by the browser
- Connection: Type of link between browser and server
- Cookies: Any cookie that is set on the current page
- Host: The domain of the page where the request was made
- Referer: URI of the issuing request page
- User-agent: User agent string for browser
The following image is a screenshot of the network under my Chrome developer tool, which you can refer to:
The beauty of JavaScript Ajax