JavaScript series----Ajax and cross-domain communication

Source: Internet
Author: User
Tags deprecated script tag domain server

1.ajax1.1.ajax Introduction

Ajax introduction This part of our main talk about the origin of Ajax, what is Ajax? Because these are technology-independent. So, most of the details are a stroke.

The origins of Ajax?

The word Ajax stems from a 2005-year-old Jesse James Garrett, titled "Ajax:a New Approach to WEB applications". He introduced a new technology in this article, which he said was 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 having to unload the page. Since the advent of this technology, Microsoft has pioneered the introduction of Xhrt objects (the core object that Ajax can implement), and other browsers have implemented this technology in succession. In a word, 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 at the time. There are three different versions of XHR objects in IE:msxml2.xmlhttp,msxml2.xmlhttp.3.0 and msxml2.xmlhttp.6.0;

Based on these three version numbers, create a Xhr object in IE as follows:

functioncreatexhr () {//IE7 Previous versions in this way varversions = [    ' Msxml2.xmlhttp ',    ' msxml2.xmlhttp.3.0 ',    ' msxml2.xmlhttp.6.0 '  ]; varXHR =NULL;  for(varIteminchversions) {    Try{XHR=NewActiveXObject (item);//If this version does not exist, an error may occur      if(XHR) Break; } Catch(e) {//generally do not deal with this kind of mistake    }  }  returnxhr;}

After IE introduced this object, other browser vendors also follow, this time XHR objects become the de facto standard!

Create XHR objects across browsers;

 function   Createxhttprequest () { Span style= "color: #0000ff;" >if  (typeof  xmlhttprequest!== ' undefined ' //do not use the IF (XMLHttpRequest) {} form,   Span style= "color: #0000ff;"              >return  new   XMLHttpRequest (); //  
Else if (typeof ActiveXObject!== ' undefined '
return//Use the function we created just now
elsethrownew Error (' Cannot create XMLHttpRequest object ');}}

Usage of 1.2.XMLHttpRequest

There are 6 functions for a XMLHttpRequest object:

Open ("Method", URL,boolean);

The //&&                URL is the path of the current page relative to the execution code (using absolute path is allowed)&&

Send ();

Note: If there are parameters, please use post to submit using the following method, send ("user=" +username+ "&pwd=" +password); If there are no parameters, for compatibility reasons, NULL must be passed in the parameter, that is, send (null), and the method is submitted using get

Abort (); Cancels the current response, closes the connection, and ends any pending network activity.

This method resets the XMLHttpRequest object to a state of readyState 0 and cancels all pending//network activity. For example, you can call this method if the request takes too long and the response is no longer necessary.

getResponseHeader ()

Returns the value of the specified HTTP response header. Its argument is the name of the header of the HTTP response to return. You can use either//to write the name of the header, and the comparison of the response head is not case-sensitive.

The return value of the method is the value of the specified HTTP response header, or an empty string if the header is not received or Readystat//e is less than 3. If multiple headers with the specified name are received, the value of the header is concatenated and//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 all HTTP responses sent by the server

Head. The head is returned as a single string, one line at a head. Each line is separated by a line break "\ r \ n".

setRequestHeader ()

Sets or adds an HTTP request to an open, but not sent, request.

There are 5 properties for the XMLHttpRequest object:

Property Describe
ResponseText Text to be returned as a response topic
Responsexml If the response is a text/html or application/xml type, this property will hold the XML document of the response
Status Response Status code for HTTP
StatusText Description of the HTTP status
ReadyState Status bits for XMLHttpRequest objects 0 1 2 3 4 representing 5 states
Timeout Sets the time-out period in Ms. currently only ie8+ support---not yet standardized (deprecated)

Event Properties for XMLHttpRequest Objects onreadystatechange:-----All browsers compatible

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

The readystate changes correspond to the following states:

0: not initialized yet. Before open () is called

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

2: send. Call Send () but has not yet received a response.

3: Data is being received. The response data has just been received until the reception is complete.

4: complete. Data reception complete.

function () {  if (xhr.readystate = = 4)    {if (xhr.status >= && Xhr.stat US <== 300 | | Xhr.status = = 304) {      alert (xhr.responsetext)      ; // processing the received data    Else {      // request failed, response data not received     }  //Supplemental NOTE: Registration event must occur before send () 

The event properties of the XMLHttpRequest Object OnTimeOut-----Limited to ie8+, but the latest mainstream high-version browsers have also been implemented (deprecated)

xhr.timeout=1000; // One second xhr.ontimeout=Functon () {  // handling code ...   }

The problem with this usage is that after the timeout, the onReadyStateChange event is still triggered after the data is received, and if the Xhr.status property is accessed when the Onreadychange event is processed, an error occurs. So we need to do a bit of try{}catch processing when we access this property. However, because this property is temporarily incompatible, all of us are not focused.

The event properties of the XMLHttpRequest object onload onerror onloadstar onbort onprogress:

-----Non-IE browser and IE + + has been implemented

onload above IE8 can be achieved, Most events can be implemented according to readysate changes, and the above events are simply easy to use.

Both the onload and OnProgress events correspond to the readystate=4 and readystate=3, respectively, using the following methods:

     xhr.onloadfunction  (event) {            //event contains only one attribute event.target=xhr; The way to use it is just the same as when Readystate=4 .         }     xhr.onprogress=function(event) {         //  Event contains three attributes         //Lengthcomputale (availability of progress information) in addition to EVENT.TARGET=XHR Position (bytes accepted) and TotalSize (total number of bytes).               }

Add: Some events can be simulated according to the state of 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. When the client receives the returned data, it uses the callback function to process the data.

That

1. Client requests data to an out-of-domain server

2. The server receives the response and sends the data to the client.

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

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

3.1.CORS the principle of cross-domain requests when sending an extraterritorial request with an XHR (XMLHttpRequest) object or an XDR (xdomainrequest) object, the approximate implementation principle is as follows: implementation 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.

Features of XHD:

1.cookie is not sent with the request and is not returned with the response.

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

3. Unable to access the response header information.

4. Just support get and post requests.

XDR supports the onload and OnError event properties and is basically consistent with the XHR, although its open () only receives two parameters, which are asynchronous by default.

var New  function  () {  // handling Xdr.responsetextfunction () {};xdr.open (' get ', ' absolute URL '); Xhr.send (null);

3.3. Cross-browser Cors technology implementation

XHR objects in standard browsers can already automatically implement cross-domain requests, but the differences between XHR and XDR are:

1.XHR you can set withcredentials =true, the browser will send a cookie to the server, the server at this time by setting the head access-control-allow-credentials:true to respond. 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.

Here's the code to implement cross-domain requests:

functioncreatecrosrequest (method, url) {varXHR =NewXMLHttpRequest ();//ie7+  if(' Withcredentials 'inchXHR) {//IE8-IE9 Browser does not have this propertyXhr.open (method, URL,true); } Else if(typeofXdomainrequest! = ' undefined ') {XHR=NewXdomainrequest ();//IEXhr.open (method, URL)}returnXHR;}
var request=createcrosrequest ("Get", "url");
if (request) {
Request.onload=function () {
Processing Request.responsetext;
}
Request.send (NULL);
}
4. Unidirectional cross-domain technology---JSONP technology

JSONP technology is relatively simple, the main principle is the use of script tag characteristics.

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

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

If we request, the returned data is callback + ' (' + JSON + ') '; This form of data, the callback () function can be executed automatically after the script is loaded.

4.1. Client-side notation
<! DOCTYPE html>window.onload=function(){        varButton=document.getelementbyid ("IButton"); functionCallback (data) {//Processing Data} Button.onclick=function(){            varScript=document.createelement ("Script"); Script= "Http://www.sasd.com/json/?callbak=callback"; Document.body.insertBefore (script,document.body.firstchild);//Load Script}}</script>

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

A cross-domain request is sent when the 2.script is loaded.

4.2. Server-side

1. Get the function name by URL, named callback

2. Convert the requested data into JSON format as a function's parameter format, named.

3. Stitching the results back into callback+ "(" +json+ ")"; --------is to return the populated data, which is automatically executed in the script.

4. Return data.

Disadvantages of 4.3.JSONP Technology

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

2.<script> currently only OnLoad property events, OnError has not been unified, if the loading script error, the client is very 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, it is more harmful and difficult to discover.

JavaScript series----Ajax and cross-domain communication

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.