JavaScript Advanced Programming notes (21)

Source: Internet
Author: User

Ajax and Comet

Ajax can request additional data from the server without uninstalling the page.

The core of Ajax technology is the XMLHttpRequest object (abbreviated as XHR). You can use the XHR object to get new data, and then insert new data into the page through the DOM, and Ajax communication is not necessarily XML data, regardless of the data format.

(i) XMLHttpRequest object

IE 7+ Firefox Opera chorme Safari supports native XHR objects, using XMLHttpRequest constructor var xhr = new XMLHttpRequest ();

If you want to support the early version of IE

        functioncreatexhr () {if(typeofXMLHttpRequest! = "undefined"){                return NewXMLHttpRequest (); } Else if(typeofActiveXObject! = "undefined"){                if(typeofArguments.callee.activeXString! = "string"){                    varversions = ["msxml2.xmlhttp.6.0", "msxml2.xmlhttp.3.0",                                    "Msxml2.xmlhttp"], I, Len;  for(i=0,len=versions.length; i < Len; i++){                        Try {                            NewActiveXObject (Versions[i]); Arguments.callee.activeXString=Versions[i];  Break; } Catch(ex) {//Skip                        }                    }                }                            return NewActiveXObject (arguments.callee.activeXString); } Else {                Throw NewError ("No XHR object available.")); }        }

Usage of 1.XHR

When using the Xhr object, the first method to invoke is open (), which receives 3 parameters: the type of request to send (get, post, etc.), the URL of the request, and the Boolean value that represents whether the request was sent asynchronously, such as:

Xhr.open ("Get", "example.php",false)

The URL corresponds to the current page of the execution code, and calling the open () method does not actually send the request, just initiates a request for sending.

To send a specific request, call the Send () method: Xhr.send (NULL). If you do not need to send data through the request principal, you must pass in null, and after calling Send (), the request is dispatched to the server.

Properties of the Xhr object:

ResponseText: The text returned by the response body

Responsexml: If the content type of the response is "text/xml" or "application/xml", this property will hold the HTTP state that contains the corresponding data.

Status: The HTTP status of the response.

Description of the Statustext:http status.

The HTTP status code can typically be 200 as a flag for successful response. A status code of 304 indicates that the requested resource has not been modified and can be used directly from the browser's cached version.

The contents of the response body are saved to the ResponseText property, and the value of the Responsexml property is 0 for non-XML data.

The ReadyState property represents the current active phase of the request/response process:

0: The Open () method is not called for initialization.

1: Start. The open () method was called, but the Send () method was not called.

2: Send. The Send () method was called, but the response was not received.

3: Receive. Partial response data has been received

4: Complete. All response data has been received and can be used on the client.

As long as the value of readystate changes, the ReadyStateChange event is triggered, which can be used to detect the value of readystate. Generally only 4 is detected. The onReadyStateChange event handler must be developed before calling open ().

Xhr.onreadystatechange =function(event) {//the current active phase of the request/corresponding process            if(Xhr.readystate = = 4){                //HTTP status Code                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);

You can call the Abort () method to cancel an asynchronous request before receiving a response.

2.HTTP Header Information

The setRequestHeader () method can set the custom request header information to receive two parameters: the name of the header field and the value of the header field. It must be called before calling Send () after the call to open ().

3.GET Request

Get is the most common request and is most commonly used to query the server for information. If necessary, you can add the query string to the end of the URL.

The name and value of each parameter in the query string must be encoded with encodeuricomponent () before it can be placed at the end of the URL. and all name-value pairs must be separated by &.

Xhr.open ("Get", "Example.php?name1=value1&name2=value2",true );

4.POST Request

Typically used to send data that should be saved to the server.

First step: The first parameter of the open () method passes in the "post"

Step Two: Pass some data to the Send () method.

Use XHR to mimic a form submission: Set the Context-type header information to application/x-www-form-unlencoded, which is the type of content at the time the form commits, and then create a string in the appropriate format.

(ii) XMLHttpRequest level 2 1. FormData

Formdata type: Serializes the form, creating the same data as the form format.

var New FormData ();d ata.append ("name", "Nico")

The append () method receives two parameters: a key and a value. By passing in the form element to the Formdata constructor, you can fill in the keys and values with the data of the form element.

2. Timeout settings

The timeout attribute in ie8+ indicates that the request terminates after waiting for the corresponding number of milliseconds. If the browser does not accept the corresponding time, the timeout event is triggered and the OnTimeOut event handler is called.

        true );         = +;         function () {            alert ("Request did not return in a second.") );        };                Xhr.send (null);

3.overrideMimeType () method

Used to override the XHR corresponding MIME type, because the MIME type of the returned response determines how the XHR object handles it, so it is useful to be able to rewrite the MIME type returned by the server.

Firefox, Safari 4+, Opera 10.5, Chrome

(iii) Progress events

Defines events related to client server communication, at the earliest, only for XHR operations, and is currently being referenced by other APIs.

Progress event: Loadstart progress error Abort load loaded

Each request starts with the triggering Loadstart event, followed by one or more progress events, and then triggers one of the error, abort, or load events, and finally triggers the loaded.

Firefox 3.5+ Safari 4+ Chrome IE8 only supports load

1.load Events

The Load event is triggered when the corresponding receive is complete, and its target property points to the Xhr object instance, which can access all methods and properties of the Xhr object. The load event is triggered whenever the browser receives the server, so the status property is detected.

2.progress Events

Triggered periodically while the browser is receiving new data. The OnProgress event handler receives an event object whose target property is the Xhr object and contains three additional properties: lengthcomputable, Position, and totalsize.

Lengthcomputable: Boolean value of whether progress information is available.

Position: The number of bytes that have been received.

TotalSize: The expected number of bytes determined based on the Content-length response header.

You must add the OnProgress event handler before calling the Open method.

(iv) Cross-origin resource sharing

Cors defines how the browser and the server should communicate when the cross-origin resource must be accessed again.

The idea of cors is to use a custom HTTP header to let the browser communicate with the server to determine whether the request or response was successful.

If the server task request is acceptable, the same source information is sent back in the Access-control-allow-origin header.

1.IE implementation of Cors

XDR objects are used in a similar way to XHR, creating an instance of Xdomainrequest, calling the open () method, and then calling the Send () method. Only two parameters are accepted: The type of the request and the URL.

All XDR requests are executed asynchronously, the load event is triggered after the request is returned, and the data is saved in the ResponseText property.

2. Other browser-to-cors implementations

The Firefox 3.5+ safari4+ Opera XMLHttpRequest object implements native support for Cors. Use the XHR object and pass in the absolute URL in the open () method when requesting resources for another domain. The status and StatusText properties can be accessed through cross-domain XHR objects, and synchronization requests are also supported. But there are some limitations.

3.Preflighted Requests

Preflighted requests: Transparent server Authentication mechanism that enables developers to use custom headers, get or post methods, and different types of principal content.

Firefox 3.5+ Safari 4+ Chrome IE10 and not previously supported

4. Request with credentials

You can specify that a request should send credentials by setting the Withcredentials property to True.

Firefox 3.5+ Safari 4+ Chrome IE10 and not previously supported

5. Cross-browser Cors

The simplest way to detect whether XHR supports cors is to check for the presence of withcredentials attributes, and then combine to detect the presence of Xdomainrequest objects.

(v) Other cross-domain technologies

1. Image Ping

Dynamically create images, using their onload and onerror event handlers to determine if they are received appropriately.

Most commonly used to track user clicks or dynamic ad exposure times. Disadvantage: Only get requests can be sent, and the corresponding text of the server cannot be accessed.

2.JSONP

The JSON that is contained in a function call 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.

3.Comet

is a technique by which servers push data to a page, allowing information to be pushed to the page in near real time.

Implementation mode: Long polling and streaming.

The benefits of polling are supported by all browsers, and can be implemented using XHR objects and settimeout ().

HTTP streaming: The browser sends a request to the server, the server keeps the link open, and periodically sends the data to the browser. All server-side languages support printing to the output cache and then updating.

Firefox Safari Opera Chrome can implement HTTP streaming with XHR objects by listening to the ReadyStateChange event and detecting whether the value of Readysatate is 3.

  

4. Server sends events

SSE is an API or mode that is launched around a read-only comet switch. The SSE API is used to create a one-way link to a server where the number of tasks can occur through this connection. The corresponding MIME type of the server must be Text/event-stream, and the JavaScript API of the dish can parse the output of the format.

Firefox 6+ Safari 5+ opera11+ Chrome

You first create a new EventSource object and transfer an entry point. The incoming URL is the same as the page that created the object.

5.Web Sockets

Provides duplex, bidirectional communication on a unique persistent link. The standard HTTP server cannot implement Web Sockets, only dedicated servers that support this protocol can work.

The advantage of using a custom protocol instead of the HTTP protocol is that it can send very small amounts of data between the client and the server. Make sure that the protocol is set longer than the JavaScript API.

Firefox 6+ Safari 5+ Chrome

①web Sockets API

To create a Web Sockets, first instantiate a Web Sockets object and pass in the URL to be linked (absolute).

② Sending and receiving data

To send data to the browser, use the Send () method and pass in any string. WEB sockets can only send plain text data over a connection, and for complex data structures, it is serialized before being sent over a connection. The Web Sockets object triggers a message event when the server sends data to the client.

③ Additional Events

Open Error Close

6.SSE and Web Sockets

Is there any freedom to establish and maintain a Web sockets server

Do not need two-way communication.

(vi) Security

To ensure that URLs accessed through XHR are secure, it is common practice to verify that the sending requestor has access to the appropriate resources.

JavaScript Advanced Programming notes (21)

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.