[Notes] JavaScript advanced programming-Ajax and Comet

Source: Internet
Author: User
Tags xml dom document ssl connection

Before the advent of XHR, Ajax-style communications had to be implemented with some hack means, mostly using hidden or inline frames.

First, XMLHttpRequest Object

1 usage of XHR

When using a Xhr object, the first method to invoke is open (), which accepts 3 parameters: the type of request to be sent ("get", "post", and so on), the requested URL, and a Boolean value that represents whether the request was sent asynchronously.

To send a specific request, you must call the Send () method as follows. The Send () method accepts a parameter as the data sent by the requesting principal. If you do not need to send data by requesting a topic, you must pass in NULL, because this parameter is required for some browsers.

When the request is synchronized, the JavaScript code waits for the server to respond before continuing. After the response is received, the data for the response is automatically populated with the properties of the Xhr object, as described in the related properties.

    • ResponseText: The text to be returned as the response body.
    • Responsexml: If the content type of the response is "text/xml" or "application/xml", this property will hold the XML DOM document containing the response data.
    • Status: The HTTP status of the response.
    • StatusText: Description of the status code.

After accepting the response, the first step is to check the Status property to determine that the response has returned successfully. In general, an HTTP status code of 200 can be used as a success flag. At this point, the content of the ResponseText property is ready, and responsexml should be able to access it if the content type is correct. At this point, a status code of 304 indicates that the requested resource has not been modified and can be used directly from the cached version in the browser, which, of course, means that the response is valid.

The ReadyState property of the Xhr object that represents the current active phase of the request/response process. The following values are desirable for this property.

    • 0: not initialized. The open () method has not been called.
    • 1: Start. The open () method has been called, but the Send () method has not been called.
    • 2: Send. The Send () method has been called, but the response has not been received.
    • 3: Accept. Part of the response data has been received.
    • 4: Complete. All the response data has been received and can already be used on the client.

A readystatechange time is triggered whenever the value of the ReadyState property is changed from one value to another. This event can be used to detect the value of readystate after each state change.

You can also call the Abort () method to cancel an asynchronous request before accepting the response, as follows.

Xhr.abort ();

When this method is called, the XHR object stops triggering the event, and no longer allows access to any object properties related to the response. After the request is terminated, the XHR object should also be dereferenced. Because of memory reasons, it is not recommended to use the XHR object.

2 HTTP header information

The Xhr object also provides methods for manipulating the request header and the response header information.

    • Accept: The type of content that the browser can handle.
    • Accept-charset: The character set that the browser can display.
    • Accept-encoding: The compression encoding that the browser can handle.
    • Accept-language: The language currently set by the browser.
    • Connection: The type of connection between the browser and the server.
    • Cookie: Any cookie that is set on the current page.
    • Host: The domain of the page where the request was made.
    • Referer: The URI of the page that issued the request.
    • User-agent: The user agent string for the browser.

Use the setRequestHeader () method to set the custom request header information. This method takes two parameters: the name of the header field and the value of the header field. To successfully send the request header information, you must call setRequestHeader () before calling the Send () method after the open () method is called.

3 GET Request

For XHR, the query string at the end of the URL to the incoming open () method must be correctly encoded. The name and value of each parameter in the query string must be encoded with encodeuricomponet () before it can be placed at the end of the URL, and all name-value pairs must be delimited by the number (&).

4 POST Request

Use XHR to mimic form submissions: First set the Content-type header information to application/x-www-form-urlencoded, which is the type of content when the form is submitted, followed by creating a string in the appropriate format. The post data is in the same format as the query string.

Second, XMLHttpRequest Level 2

1 FormData

Formdata is used to serialize the form and create the same data as the form format (for transmission through XHR).

The following code creates a Formdata object and adds some data to it.

var data = new FormData ();d ata.append ("name""Nicholas" );

The Append () method accepts two parameters: a key and a value that correspond to the name of the form field and the value contained in it. Any number of key-value pairs can be added as above. You can also use the data from the form element to fill in the key-value pairs in advance by thinking of passing in the form element in the Formdata constructor:

var data = new FormData (document.forms[0]);

Once you have created an instance of Formdata, you can pass it directly to the XHR send () method.

The convenience of using formdata is reflected in the need to explicitly re-xhr the object on the set of the request header. The XHR object is able to recognize that the incoming data type is an instance of Formdata and configures the appropriate header information.

2 Timeout definitions

IE8 adds a timeout property to the Xhr object, indicating how many milliseconds the request waits for a response to terminate. After setting a value for timeout, if the browser has not received a response within the specified time, the timeout event is triggered and the OnTimeOut event handler is called. This feature was later also paid for in the XMLHttpRequest Level 2 specification.

3 Overridemimetype () method

Firefox first introduced the Overridemimetype () method, which overrides the MIME type of the XHR response. This method is also included in the XMLHttpRequest Level 2 specification. Because the MIME type of the return response determines the xhr of how you handle it, it is useful to have a way to rewrite the MIME type returned by the server.

Iii. Progress Events

The prograssevents specification is a working draft of the network, defining events related to client server communication. These events were originally intended only for XHR operations, but are now also referenced by other APIs. The following 6 progress events are available.

    • Loadstart: Triggered when the first byte of a response data is received.
    • Progress: constant triggering during acceptance of the response.
    • Error: triggered when a request error occurs.
    • Abort: Triggered when the connection should be terminated for calling the Abort () method.
    • Load: Triggered when the full response data is received.
    • Loadend: Triggered after communication completes or triggers an error, abort, or Load event.

Each request starts with triggering the Loadstart event, followed by one or more progress events, then triggering an error, abort, or one of the load events, ending with the triggering Loadend event.

Iv. cross-domain resource sharing

One of the main limitations of Ajax communication through XHR is the cross-domain security policy.

CORS (Cross-origin Resource sharing, cross-domain security resource sharing) is a working draft that defines how browsers and servers should communicate when cross-domain resources must be accessed. The basic idea behind cors is to have the browser communicate with the server using a custom HTTP header to determine whether the request or response should succeed or should fail.

1 IE's implementation of cors

Microsoft introduced the XDR (xdomainrequest) type in IE8. This object is similar to XHR, but it enables secure and reliable cross-domain communication.

    • The cookie is not sent with the request and is not returned with the response.
    • Only the Conent-type field in the request header information can be set.
    • Unable to access the response header information.
    • Only get and post requests are supported.

2 other browsers ' implementations of Cors

WebKit native support for cors is achieved through the XMLHttpRequest object. To request a resource that resides in another domain, use the standard XHR object and pass in the absolute URL in the open () method.

There are also restrictions on cross-domain XHR objects.

    • You cannot use setRequestHeader () to set a custom header.
    • Cookies cannot be sent and accepted.
    • Calling the getAllResponseHeaders () method always returns an empty string.

V. Other cross-Domain technologies

1 Image Ping

Image Ping is a way of making simple, one-way, cross-domain communications with the server. The requested data is sent as a query string, and the response can be anything but usually a pixel graph or a 204 response. With an image ping, the browser does not get any specific data, but by listening to the load and error events, it can know when the response was received.

var New  function() {    alert (' done! '  = ' Http://www.example.com/test?name=Nicholas ';

The two main drawbacks of Ping are that only get requests can be sent, and the response text of the server cannot be accessed. Therefore, the image ping can only be used for single communication between the browser and the server.

There are two main drawbacks to image Ping, one is that you can only send a GET request, but you cannot access the response text of the server.

2 JSONP

JSONP is a shorthand for JSON with padding (filled JSON or parametric json). Jsonp looks like JSON, except for the JSON contained in the function call, as follows.

Callback ({"Name": "Nicholas"});

JSONP consists of two parts: the callback function and the data. A callback function is a function that should be called in the page when the response arrives. The name of the callback function is typically specified in the request. The data is the JSON data that is passed into the callback function.

JSONP is used by dynamic <script> elements, and can be used to specify a cross-domain URL for the src attribute. Because JSONP is a valid JavaScript code, it executes immediately after the request is completed, after the JSONP response is loaded into the page.

Compared to the image Ping, his advantage is the ability to directly access the response text, enabling two-way communication between the browser and the server. However, Jsonp also has two points.

First JSONP is the load code execution from the other domain. If the other domains are unsafe, it is likely that some malicious code will be entrained in the response, and there is no way to pursue this at this point except to completely abandon the JSONP call. So when using a Web service that is not your own operation, make sure it is safe and secure.

Second, it is not easy to determine whether JSONP requests fail. Although HTML5 has added a onerror event handler to the <script> element, it has not yet been supported by any browsers. To do this, the developer had to use a timer to detect whether a response was received within the specified time. But even if this is not satisfactory, after all, not every user online speed and bandwidth are the same.

3 Comet

Comet is a technique by which servers push data to a page. Comet enables information to be pushed to the page in near real time, making it ideal for handling sporting scores and stock quotes.

There are two ways to implement comet: long polling and streaming. Long polling is a replica of a traditional polling (also called a short poll) where the browser sends the request periodically to see if there is any updated data.

A short poll is a server that sends a response immediately, regardless of whether the data is valid, and long polling is waiting for a response to be sent. The advantage of polling is that all browsers support it because it is possible to use XHR objects and settimeout (). And all you have to do is decide what to send.

The second popular Comet implementation is the HTTP stream. The stream differs from both of these polls because it uses only one HTTP connection for the entire life of the page. Specifically, the browser sends a request to the server, and the server keeps the connection open, and then periodically sends the data to the browser.

All server-side languages support the ability to print to the output cache and then refresh (send content from the output cache all at once to the client). This is the key to implementing HTTP streaming.

By listening for the ReadyStateChange event and detecting whether the value of readystate is 3, you can implement an HTTP stream with the Xhr object. In these browsers, as you continue to receive data from the server, the value of readystate is periodically changed to 3. When the readystate value changes to 3, all received data is saved in the ResponseText property. At this point, you need to compare the previously received data and decide where to start getting the latest data. The typical code for implementing an HTTP stream using the XHR object is shown below.

functioncreatestreamingcilent (URL, progress, finished) {varXHR =NewXMLHttpRequest (), Received= 0; Xhr.open (' Get ', url,true); Xhr.onreadystatechange=function() {        varresult; if(Xhr.readystate = = 3) {result=xhr.responseText.substring (receivied); Received+=result.length;        Progress (result); } Else if(Xhr.readystate = = 4) {finished (xhr.responsetext);    }    }; Xhr.send (NULL); returnxhr;}varClient = createstreamingclient (' streaming.php ', Fucntion (data) {alert ("Received" +data);},function(data) {alert ("Done!");});

4 Server Send Events

SSE (server-sent events, Server send event) is an API or pattern that is introduced around read-only comet interaction.

5 Web Sockets

The goal of the WebSockets is to provide full-duplex, bidirectional communication on a single, persistent connection. After WebSocket is created in JavaScript, an HTTP request is sent to the browser to initiate the connection. After the server response is obtained, the established link is switched from the HTTP protocol to the WebSocket protocol using an HTTP upgrade.

Because WebSockets uses a custom protocol, the URL pattern is slightly different. Unencrypted connections are no longer http://, but ws://; encrypted connections are not https://, but wss://. This pattern must be used when using the WebSocket URL, as it is possible to support other schemas in the future.

The advantage of using a custom protocol instead of the HTTP protocol is the ability to send very small amounts of data between the client and the server, without worrying about the byte-level overhead of HTTP.

Vi. Security

In the case of unauthorized systems having access to a resource, we call it CSRF (Cross-site request forgery, cross-site requests forgery). To ensure that URLs accessed through XHR are secure, it is common practice to verify that the sender has access to the response's resources. There are several ways to choose from:

    • Requires an SSL connection to access resources that can be requested through XHR.
    • Requires that each request be accompanied by a corresponding calculated verification code.

The following measures do not work against CSRF attacks.

    • Asking to send a post instead of a GET request--it's easy to change.
    • Check the source URL to determine if it is trustworthy-the source record is easy to forge.
    • Authentication based on cookie information--it's also easy to forge.

[Notes] 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.