JavaScript Advanced Programming Chapter 21st: Ajax and Comet

Source: Internet
Author: User

The technical core of Ajax is the XMLHttpRequest object (abbreviated as XHR)

First, create XMLHttpRequest object
1     functioncreatexhr () {2         if(typeofXMLHttpRequest! = "undefined"){3             //IE7, FireFox, Opera, Chrome, Safari all support native XHR objects, and these browsers can use the XMLHttpRequest constructor4             return NewXMLHttpRequest (); 5}Else if(typeofActiveXObject! = "undefined"){6             //used in versions prior to IE77             if(typeofArguments.callee.activeXString! = ' String '){8                 varversions = ["msxml2.xmlhttp.6.0", "msxml2.xmlhttp.3.0",9"Msxml2.xmlhttp"],Ten I, Len; One                  for(I=0, len=versions.length; i<len; i++){ A                     Try{ -                         NewActiveXObject (Versions[i]); -Arguments.callee.activeXString =Versions[i]; the                          Break; -}Catch(ex) { -                         //Skip over -                     } +                 } -             } +             return NewActiveXObject (arguments.callee.activeXString); A}Else { at             Throw NewError ("No XHR object Available"); -         } -     } -  -     //Create a Xhr object -     varXHR = CREATEXHR ();
Second, the use of XHR 1. Open () Method:
      • Three parameters: the type of request sent, the URL of the request, whether to send asynchronously
      • Attention:
        • URL relative to the current page of the execution code (you can also use an absolute path)
        • Calling the open () method does not actually send the request, but only initiates a request for sending
        • Requests can only be sent to URLs that use the same port and protocol in the same domain , and if there is any difference between the URL and the page that initiated the request, a security error will be raised!
2. Send request: Send () method
      • Receives a parameter, which is the data to be sent as the request principal.
      • If you do not need to send data through the request principal, you must pass in NULL. This parameter is required for some browsers.
3. When the response is received, the response data is automatically populated with the properties of the Xhr object. The related properties are:
      • ResponseText
      • Responsexml
      • Status
      • StatusText

When a response is received, the status property is checked first , and in general, the HTTP status code of 200 is used as the success flag. In addition, the status code 304 indicates that the requested resource has not been modified and can be used directly from the cached version in the browser, and the response is also valid.

For asynchronous requests, you can detect the Readystatus property of the Xhr object, which represents the current active phase of the request/response process, with the following values:

      • 0: not initialized. The open () method has not been called
      • 1: Start. The open () method has been called and the Send () method has not been called
      • 2: Send. The Send () method has been called and the response has not been received
      • 3: Receive. Partial response data has been received.
      • 4: Complete. All the response data has been received and can already be used on the client. "Generally only check this stage"

A ReadyStateChange event is triggered whenever the Readystatus property is changed.

1     varXHR =createxhr ();2     //You must specify the onReadyStateChange event handler before the open () method to ensure cross-browser compatibility3Xhr.onreadystatechange =function(){4         //The XHR object is used here instead of the this object because of the scope problem of this event5         //If the This object is used, there are browsers in which the function execution fails or causes an error to occur. 6         if(Xhr.readystate = = 4){7             if((xhr.status >= && xhr.status <300) | | xhr.status = 304){8 alert (xhr.responsetext);9}Else {TenAlert ("Request was unsuccessful:" +xhr.status); One             } A         } -     }; -Xhr.open ("Get", "Example.txt",true); theXhr.send (NULL);

Third, XMLHttpRequest Level 2

Iv. Progress Events

Five, cross-domain resource sharing 1. Cross-domain:

Cross-domain Security policy: By default, the XHR object can only access resources that are in the same domain as the page that contains it.

The so-called cross-domain, is because of the JavaScript homologous policy restrictions, a.com domain name JS can not operate B.Com or c.a.com the object under the domain name.

In simple terms, the same origin policy refers to a script that can read only the properties of windows and documents from the same source, where the same source refers to a combination of host names , protocols , and port numbers .

URL

Description

Whether to allow communication

http://www.a.com/a.js
Http://www.a.com/b.js
under the same domain name Allow
http://www.a.com/lab/a.js
http://www.a.com/script/b.js
different folders under the same domain allow
http://www.a.com:8000/a.js
http://www.a.com/b.js
same domain name, different ports do not allow
http://www.a.com/a.js
https://www.a.com/b.js
same domain name, different protocol do not allow
htt P://www.a.com/a.js
http://70.32.92.74/b.js
domain name and domain name corresponding IP do not allow
http://www.a.com /a.js
Http://script.a.com/b.js
primary domain same, subdomain different not allowed
http://www.a.com/a.js
Htt P://a.com/b.js
Same domain name, different level two domain name (ibid.) not allowed (cookies are not allowed in this case)
http://www.cnblogs.com /a.js
Http://www.a.com/b.js
different domain names do not allow

2. Cross-domain resource sharing (cors,cross-origin Resource sharing)

is the standard.

Basic idea: Use a custom HTTP header to let the browser communicate with the server to determine whether the request or the corresponding should be successful or should fail. (This piece of stuff looks annoying, first of all)

Vi. other cross-domain technologies 1. Image Ping

Even with tags . Because a Web page can load images from any Web page without worrying about cross-domain.

The requested data is sent in the form of a query string , and the response can be anything . With an image ping, the browser does not get any specific data, but by listening to the load and error events, you can know when the response was received.

  

 1  var  img = new   Image ();  2   The onload and OnError event handlers are specified as the same function. This way, no matter what the response, as long as the request is complete, you will be notified.  3  img.onload = Img.onerror = function
     () { 4  alert (' Done ' ); 5  };  6   The request starts at the moment the SRC attribute is set, where a name parameter is sent in the request  7  img.src= ' Http://xxxxxxxx/test? Name=nicholas '; 

  Disadvantages:

      • Only get requests can be sent
      • Unable to access the response text of the server
      • So it can only be used for one-way communication between browser and server

2. JSONP (JSON with padding, padded json/parametric json)

is a JSON that is contained in a function call. Consists of two parts:

1) callback function: The function that should be called in the page when the response arrives. Typically specified in the request

2) Data: JSON data passed into the callback function

JSONP is used with dynamic <script> elements, and when used, you can specify a cross-domain URL for the src attribute. This script, like the IMG element, has the ability to load resources from other domains without restriction. Because JSONP is a valid JavaScript code, it executes immediately after the request is completed, after the JSONP response is loaded into the page.

1     functionHandleresponse (response) {2Alert ("You were at IP address" + Response.ip + ", which was in" +3Response.city + "," + response.region_name);//try to really can pop up my address!!! 4     }5 6     varScript = document.createelement ("Script"); 7SCRIPT.SRC = "Http://freegeoip.net/json/?callback=handleResponse"; Specifies that the callback function is Handleresponse ()8Document.body.insertBefore (Script,document.body.firstchild);

Compared to the picture ping, the advantages of JSONP are:

1) Direct access to response text

2) supports two-way communication between the browser and the server.

Insufficient:

1) JSONP is the load code execution from other domains. Security in other domains is difficult to guarantee

2) It is not easy to ensure that JSONP requests fail. The OnError event handler for the <script> element is not supported by the browser, so a timer must be used to detect whether a response is received within the specified time. However, the user's Internet speed and bandwidth are not necessarily.

Vii. Security

JavaScript Advanced Programming Chapter 21st: Ajax and Comet

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.