Detailed Ajax mechanisms and cross-domain communication _ajax related

Source: Internet
Author: User
Tags http request script tag send cookies

1.Ajax

1.1.Ajax Introduction
Introduction to Ajax This part of our main focus is on the origins of Ajax, what is Ajax? Because these are not related to technology. Therefore, most of the details are a stroke.

The origins of Ajax?

The word Ajax originated from Jesse James Garrett, 2005, who published an article titled "Ajax:a New Approach to WEB applications". In this article he introduced a new technology, in his words, that is Ajax:asy Nchronous the abbreviation for JavaScript +xml.

What is Ajax?

The main purpose of this new technology is to enable front-end Web pages to request additional data from the server without unloading the page. Since the advent of this technology, Microsoft has pioneered the introduction of Xhrt objects (the core objects that Ajax can implement), and other browsers have implemented this technology successively. In short, Ajax is a technology that can communicate asynchronously.

1.2.Ajax Core Object---XMLHttpRequest
Because IE5 was the first to introduce this XHR object, there was no de facto standard. There are three different versions of XHR objects in IE: msxml2.xmlhttp,msxml2.xmlhttp.3.0 and msxml2.xmlhttp.6.0;

According to these three version numbers, create a Xhr object in IE as follows:

function createxhr () {//ie7 Previous version in this way
var versions = [
' Msxml2.xmlhttp ',
' msxml2.xmlhttp.3.0 ',
' msxml2.xmlhttp.6.0 '
];
var xhr = null;
For (var item in versions) {
try {
XHR = new ActiveXObject (item); If this version is not present, there may be an error
if (XHR) break;
catch (e) {
Generally do not deal with this kind of error
}
}
return XHR;
}
After IE introduced this object, other browser vendors also followed, when the Xhr object became the de facto standard!

Create XHR objects across browsers;

function Createxhttprequest () {
if (typeof XMLHttpRequest!== ' undefined ') {//Not in the form of if (XMLHttpRequest) {}
return new XMLHttpRequest (); If this form is not found in the XMLHttpRequest function, the error will be.
else if (typeof activexobject!== ' undefined ') {
return createxhr (); Using the function that we just created
else {throw new Error (' Cannot create XMLHttpRequest object ');}

The use of 1.2.XMLHttpRequest
There are 6 functions for the XMLHttpRequest object:

Open ("Method", Url,boolean);    
           The three parameters of the method,//&& URLs such as----commit "get" or "post", are the paths of the current page relative to the execution code (which is allowed using an absolute path) && asynchronous Send (); This method receives a parameter, which is the data sent as the request body,//Description: If there are parameters, please submit using the Post method as follows, send ("user=" +username+ "&pwd="
           +password);       If there are no parameters, for compatibility reasons, you must pass in a null in the parameter, that is, send (null); This method submits the abort () using the Get method;

          Cancels the current response, closes the connection, and ends any pending network activity. This method resets the XMLHttpRequest object to the state of ReadyState 0 and cancels all pending//network activity.

For example, this method can be invoked if the request takes too long and the response is no longer necessary. getResponseHeader ()//Returns the value of the specified HTTP response header. The parameter is the name of the HTTP response header to return.

          The header name can be drawn using either//, and the comparison of the response head is case-insensitive. The return value of the method is the value of the specified HTTP response head, or an empty string if the header is not received or if the Readystat//e is less than 3.

If you receive multiple headers with the specified name, the value of the header is concatenated and/or returned, separating the values of each head with commas and spaces.

          getAllResponseHeaders ()//Returns the HTTP response header as an unresolved string. If ReadyState is less than 3, this method returns NULL. Otherwise, it returns the//head of all HTTP responses sent by the server. The head is returned as a single string, one head at a row. NewLine characters per line "\ r \ nSeparated

 setRequestHeader ()//set or add an HTTP request to an open but unsent request.

There are 5 properties for the XMLHttpRequest object:

Attribute description
ResponseText the text returned as a response topic
Responsexml If the response is a text/html or application/xml type, this property will hold the XML document for the response
The status HTTP response status code
Description of StatusText HTTP status
ReadyState XMLHttpRequest object's state bit 0 1 2 3 4 represents 5 states respectively
Timeout sets the timeout in units of Ms. Currently only ie8+ support---not yet standardized (not recommended)

XMLHttpRequest object's Event property onreadystatechange:-----All Browser compatible

This property listens for changes to the ReadyState property of the XMLHttpRequest object:

The changes of readystate correspond to the following States respectively:

0: not initialized. Before calling Open ()

1: Start up. After calling open (), but send () is not invoked;

2: Send. Call Send () but has not been responded to.

3: Receiving data. Just received the response data before the receive completes.

4: Finished. Data reception completed.

Xhr.onreadystatechange = function () {
 if (xhr.readystate = 4) {
  if (xhr.status >= && Xhr.status & lt;== 300 | | Xhr.status = = 304) {
   alert (xhr.responsetext);
   Processing received data
  } else {
   //request failed, no response data}}
;//Supplemental Note: Registration event must occur before send ()

The event properties of the XMLHttpRequest object ontimeout-----Only ie8+, but the latest mainstream high-version browsers have been implemented (deprecated)

xhr.timeout=1000;//a second.

Xhr.ontimeout=functon () {
Handling code
......
}
One problem with this usage is that after the timeout, the onReadyStateChange event is still triggered after the data is received, and an error occurs if the Xhr.status property is accessed when the Onreadychange event is processed. So we need to do some try{}catch processing when accessing this property. However, because this attribute is temporarily incompatible, all of us will not focus on the talk.

XMLHttpRequest object's Event properties onload onerror Onloadstar onbort onprogress:

-----non IE browser and IE 10+ are implemented

OnLoad in IE8 above can be achieved, most of the events according to readysate changes can be achieved, the above events are simply convenient to use.

The onload and OnProgress events correspond to the readystate=4 and readystate=3 respectively, and are used in the following ways:

   The Xhr.onload= function (event) {
      //event contains only one property event.target=xhr, which is just about the same as when readystate=4.
    }
   Xhr.onprogress=function (event) {
     //event contains three properties
     //lengthcomputale (Progress information is available) in addition to EVENT.TARGET=XHR. Position (number of bytes accepted) and TotalSize (total bytes).
     
   }


Add: Some events can be simulated according to the state of the readystate. Only some browsers are easy to handle.

3. One-way Cross-domain Technology---CORS
Today we are talking about client pages requesting data from servers that are not in the same domain. The client handles the data with the callback function when it receives the returned data.

That

1. Client requests data from an extraterritorial server

2. The server sends data to the client when it responds.

3. The client executes the callback function based on the data returned.

I know that the IFRAME under different domains can also communicate, and this is also a cross-domain communication technology. However, the two-way communication between the IFRAME pages, we explain in the next topic, today is mainly about one-way communication.

3.1.CORS cross-domain request principle
When sending an extraterritorial request with a XHR (XMLHttpRequest) object or an XDR (xdomainrequest) object, the approximate implementation principle is shown below:

Realization of cors technology in 3.2.IE
IE8 introduces an XDR type, which is basically similar to XHR, but it enables secure and reliable cross-domain communication.

Characteristics of XHD:

1.cookie is not sent with the request and will not return with the response.

2. Only content-type fragments in the request header can be set.

3. Unable to access response header information.

4. Only support get and post requests.

XDR supports the onload and OnError event properties and is used in the same way as XHR, although its open () receives only two parameters and is asynchronous by default.


var xdr = new Xdomainrequest ();
Xdr.onload = function () {
 //process Xdr.responsetext
}
xdr.onerror = function () {
};
Xdr.open (' Get ', ' absolute URL ');
Xhr.send (NULL);


3.3. Cross-browser Cors technology implementation

XHR objects in a standard browser can already automatically implement Cross-domain requests, but the difference between XHR and XDR is:

1.XHR can be set withcredentials =true, the browser will send cookies to the server, the server at this time by setting the head access-control-allow-credentials:true response. If the server does not set this property, the browser triggers the OnError event.

2. The status and StatusText properties can be accessed in the callback function, and synchronization requests are supported.

The following are the code that implements Cross-domain requests:

function Createcrosrequest (method, url) {
 var xhr = new XMLHttpRequest ();//ie7+
 if (' Withcredentials ' in xhr) {/ /IE8-IE9 Browser does not have this property
  Xhr.open (method, URL, True);
 } else if (typeof xdomainrequest!= ' undefined ') {
  xhr = new XD Omainrequest ();  IE
  Xhr.open (method, URL)
 } return
 xhr
}
var request=createcrosrequest ("Get", "url");
if (request) {
 request.onload=function () {
 //processing request.responsetext;
 }
 Request.send (null);
}

4. One-way Cross-domain Technology---JSONP technology

JSONP technology is relatively simple, the main principle is to take advantage of the characteristics of the script tag.

The script label, like the image label, has the SRC attribute, and this property is Cross-domain.

Because the script tag returns all the JS code, and the JS code is automatically executed. So, if we request the returned data is similar to the form of JS code, it is possible to implement the script after the completion of the automatic execution.

If we request, the returned data is callback + ' (' + JSON + ') '; In this form of data, the callback () function can be automatically executed after the script has finished loading.

4.1. Client-side notation

<! DOCTYPE html>
 
 

1. The client writes the callback function name to the URL parameter of the <Script> script.

The cross domain request is sent when the 2.script is loaded.

4.2. Server-side

1. Get function name by URL, named callback

2. Converts the requested data into the JSON format as a parameter format for the function, named.

3. Stitching the return result into callback+ "(" +json+ "); --------returns the filled data, which is automatically executed in the script.

4. Return data.

Disadvantages of 4.3.JSONP Technology

1. Because the parameter is passed through the URL, the request can only be a get type.

2.<script> currently only OnLoad property events, OnError has not yet unified, if the load script error, the client is difficult to get feedback.

3. The site of the requested data must be trustworthy, and if malicious code is injected into the returned data segment, the damage is greater and difficult to discover.

The above mentioned is the entire content of this article, I hope you can enjoy.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.