##1.Ajax Overview
Asynchronous JavaScript + XML, supports communication between JS and servers. Fetches new data from the server without unloading the page, to achieve better user experience (different from the traditional click-wait interaction).
IE5 provided support first, adding the XHR object (XMLHttpRequest) in the MSXML library. XHR objects can be created via new ActiveXObject(str), which although not very convenient, at least it was natively supported.
##2.XHR Object
XMLHttpRequest, [IE6-] implements the XHR object differently from other browsers, but cross-browser XHR objects can be created through object detection. The specific code is as follows:
/*Get HttpRequest object, compatible with all browsers including IE5.5+*/
function getHttpObject(){
????if(typeof XMLHttpRequest == "undefined"){//If the object is undefined, customize the object
????????XMLHttpRequest = function(){
????????????try{
????????????????return new ActiveXObject("Msxml2.XMLHTTP.6.0");
????????????}catch(e){}
????????????try{
????????????????return new ActiveXObject("Msxml2.XMLHTTP.3.0");
????????????}catch(e){}
????????????try{
????????????????return new ActiveXObject("Msxml2.XMLHTTP");
????????????}catch(e){}
????????????try{//Older versions of Internet Explorer (IE5 and IE6)
????????????????return new ActiveXObject("Microsoft.XMLHTTP");
????????????}catch(e){}
?????????????
????????????return false;
????????}
????}
?????
????return new XMLHttpRequest();
}
XHR object properties are as follows:
-
responseText: Response body
-
responseXML: If the response content is "text/xml" or "application/xml", this property holds the XML DOM document of the response data
-
status: HTTP status of the response (404, 200, etc.)
-
statusText: HTTP status description, unreliable, because browsers differ, using the status code directly is most reliable
-
readyState: Mostly used for asynchronous requests, although it can also be used for synchronous requests but it's meaningless. The 5 values of readyState are as follows:
-
0: Uninitialized. open method has not been called yet
-
1: Opened. open called but send not called
-
2: Sent. send called but response not received yet
-
3: Receiving. Partial response data has been received
-
4: Done. All data has been received and the data is now available
-
##3.Using XHR Object to Execute Callback Functions
var xhr = getHttpObject();
xhr.onreadystatechange = function(){
??if(xhr.readyState === 4){
????if(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304){//Originally only need to check 200 success and 304 not modified but some browsers may mistakenly report 200 as 204
??????//Execute callback
????}
????else{
??????//Request failed
????}
??}
}
Note: The readystatechange event handler must be set before the open function to ensure full browser compatibility.
##4.Using XHR Object to Implement Get/Post Requests
//get request
xhr.open('get', url, false/true);//Initialize, false/true ~ synchronous/asynchronous
xhr.send(null);//Send request, null is for compatibility
//post request
xhr.open('post', url, false/true);//Same as above
xhr.send(str);
/* Can set request headers after open and before send, such as adding cookie information
xhr.setRequestHeader(strHeader, strValue);
*/
Note: The server handles post requests and web form submission requests differently, but form submission can be simulated by modifying the HTTP header.
But if you want to send form data, the send parameter str must be serialized form data. At this point, you need to implement a serialization function, which is quite troublesome. JQuery provides serialization support, you can directly use $('#mForm').serialize() to serialize the form.
##5.Terminating Requests
xhr.abort(); can terminate the request before the response is returned. After abort, no more events will be triggered, and it's not allowed to access xhr's response-related properties anymore.
Note: After terminating the request, the reference to the XHR object should be released. Reusing XHR objects is not recommended (due to memory reasons).
##6.Use Post or Get?
Post requests consume more resources, and the data transmission rate is also much slower than get requests.
But get requests are insecure, and IE has restrictions on URI length (not exceeding 2048 bytes), so use get whenever possible, use post only when necessary.
##7.CORS Overview
Cross-Origin Resource Sharing, Ajax is restricted by the same-origin policy. Some CORS technologies can break the same-origin policy restrictions. For example, IE8's XDR object.
Other browsers implement native support for CORS by enhancing the XHR object: just set the url parameter of the open function to an absolute URL.
So to eliminate ambiguity, relative URLs should be used when accessing local resources, and absolute URLs when accessing remote resources.
##8.Other Cross-Origin Techniques
-
Image Ping
var img = new Image(); img.onload = img.onerror = function(){ //Response returned, execute callback function } img.src = url;//Once the src property is set, the image will be requested (loaded) immediately, not only after inserting the img element into the DOM tree
Can only send get requests, and cannot access the server's response text. Mostly used for tracking user page clicks or dynamic ad impression counts.
- JSONP
JSON with Padding, supports two-way communication between browser and server, and can directly access the response text. However, it's not easy to determine whether a request has failed, and there are security issues when loading and executing code from other domains.
There is a very goodblog post introducing cross-origin techniques
##9.CSRF Attack
Cross-Site Request Forgery, directly inserting Ajax code into a page has no same-origin policy restrictions, thus forging requests to access sensitive data.
Prevention methods include:
-
Require SSL connection to access resources
-
Require each request to include a verification code calculated by a special algorithm
No comments yet. Be the first to share your thoughts.