JavaScript advanced programming Ajax and Comet

Source: Internet
Author: User

Ajax, a shorthand for asynchronous JavaScript + XML, is a technology that can request additional technology from the server without having to unload the page, giving the user a better experience. The core of Ajax is the XMLHttpRequest object. To prevent attacks such as XSS (cross-site scripting), CSRF (cross-site request forgery), Ajax has a same-origin policy, and addresses cross-domain approaches with cors (cross-origin resource sharing), image pings, and JSONP.

Comet is an extension of Ajax, which allows the server to push data to the browser, with both long polling and HTTP streaming implementations.

WebSocket is a way to use a custom protocol for full-duplex, two-way communication with a server.

First, XMLHttpRequest Object

1. Create

Ie7+,firefox,opera,chrome and Safari both support native XHR objects, and if you want to support an earlier version of IE, you need to implement it through an ActiveX object in the MSXML library, which has three different versions, so if you want to Compatible with all browsers , the function that creates the XHR object should be defined like this:

    functioncreatexhr () {//first detect if native XMLHttpRequest exist        if(typeofXMLHttpRequest! = ' undefined '){            return NewXMLHttpRequest (); //detecting whether an active object exists}Else if(typeofActiveXObject! = ' undefined '){            if(typeofArguments.callee.activeXString! = ' String '){                //there may be 3 different versions of XML objects in IE                varversions = [' msxml2.xmlhttp.6.0 ', ' msxml2.xmlhttp.3.0 ', ' msxml2.xmlhttp ']; }             for(vari = 0, len = versions.length;i <len; i++){                Try{                    NewActiveXObject (Versions[i]); Arguments.callee.activeXString=Versions[i];  Break; }Catch(ex) {//don't do anything, skip .                }            }            return NewActiveXObject (arguments.callee.activeXString); }Else{            Throw NewError (' NO XHR object available. ')); }    }

2. Send request (GET request for example)

    var xhr = createxhr ();    Xhr.open (false//false indicates synchronous    xhr.send (null);  // write NULL if no data is sent

3, accept the response of the server

Before learning how to accept the server's response, first understand the properties associated with the XHR object:

By detecting the Readystatechage event to obtain the value of readystate, equal to 4 means that all data has been received and can be detected by the server return status:

    varXHR =createxhr (); Xhr.onreadystatechange=function(){        if(Xhr.readystate = = 4){            //because some browsers will report 204 incorrectly, so write            if((Xhr.status >= && xhr.status <) | | xhr.status = = 304) {alert (xhr.responsetext); }Else{alert (' Request was unsuccessful: ' +xhr.status); }}} Xhr.open (' Get ', ' example.txt ',true); Xhr.send (NULL);

4. Set HTTP header information when sending XHR request

HTTP header information that is sent by default:

    • Accept: Content types that the browser can handle
    • Accept-charset: The character set that the browser can display
    • Accept-encoding: Compression encoding that the browser can handle
    • Accept-language: The language currently set by the browser
    • Connection: Type of direct connection 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

To send the header information for a custom request, you must call the setRequestHeader () method between the call open () and send ():

    var xhr = createxhr ();    Xhr.open (' get ', ' Example.txt ',true);    Xhr.setrequestheader (' myheader ', ' myvalue ');    Xhr.send (null);     // get the appropriate header information    var myheader = Xhr.getresponseheader (' MyHeader ');     // get all the header information    var allheader = Xhr.getallresponseheaders ();

Second, XMLHttpRequest2 grade

XMLHttpRequest Level 2 further developed the XHR, but not all browsers have fully implemented the XMLHttpRequest Level 2 specification, the following is a description of the new part of the content:

1. Formdata Object

When sending a form using post, the form needs to be serialized and the HTTP Content-type set to applicaition/x-www-form-urlencoded (meaning that all content is encoded before it is sent to the server) ; Using the Formdata object simplifies the operation:

var New FormData (document.forms[0]); xhr.send (data);

2. Timeout property

IE8 adds a timeout property for XHR, which indicates how many milliseconds the request waits for a response to terminate.

Xhr.open (' Get ', ' test.php ',true=;   1 seconds, only for IE8function() {    alert (' Request did not return in a second. ') );} Xhr.send (null);

3. Overridemimetype () method

Overriding MIME types, such as the MIME type returned by the server is Text/plain, but the data contains the actual XML. At this time, the Responsexml property is null. By calling the Overridemimetype () method, the response is guaranteed to be processed as XML rather than plain text.

Xhr.open (' Get ', ' test.php ',true); Xhr.overridemimetype (' text/xml '); Xhr.send ( null);

Third, cross-resource sharing

1. CORS

One of the main limitations of implementing AJAX communication through XHR is the cross-domain security policy, in which the protocol, domain name, and port must be fully consistent for access. CORS (cross-origin resource sharing, cross-domain resource sharing) is a scheme that defines how communication is communicated across domain accesses. The basic idea is to use a custom HTTP header to let the browser communicate with the server to determine whether the request or response should succeed or fail. For example, on a server-side setting: access-control-allow-origin:* or Access-control-allow-origin: the specified IP.

2. Image Ping

Principle: Using the IMG tag does not have the cross-domain problem characteristic, to carry on the simple, individual cross-domain communication with the server

Disadvantage: Only get requests can be sent, the response text of the server cannot be accessed

Usage Scenario: Track the number of exposures that a user clicks on a page or dynamic ad

var New  function() {    alert (' done '= "http://www.baidu.com";

3, JSONP

JSONP is a shorthand for JSON with padding, which is implemented by specifying a URL for the SRC attribute in the dynamic <script> element (similar to the IMG tag). JSONP consists of two parts: the callback function and the data. For example: Callback ({' name ': ' Lillian '});

The name in the callback function is typically specified in the request, and the actual data requested is the data that the callback function wraps. Because JSONP is a valid JavaScript code, when the request is completed, the JSONP response is loaded into the page and is executed immediately.

Pros: Supports two-way communication between browser and server

Cons: Jsonp loading code from other domains and executing it, the security of other domains is not guaranteed; To determine if the JSONP request failed, the browser's event handlers do not support it well.

function Handleresponse (response) {    //  The code executes immediately after the request is completed }var script = Document.createelement (' script '= ' http://testtest/json?callback=handleResponse '; Document.body.insertBefore (script, document.body.firstChild);

Third, Comet

Ajax is a technique by which pages request data from a server, and comet is a technique by which servers push data to a page. There are two ways to implement this: long polling and streaming.

A short poll is when a page requests a server, regardless of whether the data is valid or not, the server responds immediately; Long polling is the server that will open until there is data to send.

The HTTP stream has only one HTTP connection throughout the page cycle. It is the browser that sends a request to the server, and the server keeps the connection open, and then periodically sends the data to the browser.

Iv. SSE and WebSocket

SSE is an API or pattern that is launched around a read-only comet interaction to create a one-way connection to the server, where the server can send arbitrary data.

WebSocket is to provide full-duplex, bidirectional communication on a single persistent connection. The HTTP protocol was superseded by a custom WS-Protocol, and the WSS protocol replaced the HTTPS protocol.

JavaScript advanced programming 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.