JavaScript Ajax and Comet detailed

Source: Internet
Author: User
Tags php script send cookies time in milliseconds xml dom document ssl connection
Javascript AJAX and Comet
Category: javascript2012-12-24 17:39 367 people read comments (0) collection report
XMLHttpRequest object
In IE5, XHR objects are implemented through ActiveX objects in the MSXML library. You may encounter three different versions of XHR objects in IE, namely MSXML2.XMLHttp, MSXML2.XMLHttp.3.0 and MXSML.XMLHttp.6.0 Versions after IE7 and other browsers will use the following functions to create:
var xhr = new XMLHttpRequest ();
Compatibility The code for creating XHR is as follows:
function createXHR () {
   if (typeof XMLHttpRequest! = "undefined") {
    return new XMLHttpRequest ();
   } else if (typeof ActiveXObject! = "undefined") {
    if (typeof arguments.callee.activeXString! = "string") {
   var versions = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp"], i, len;
   for (i = 0, len = versions.length; i <len; i ++) {
    try {
  new ActiveXObject (versions [i]);
  arguments.callee.activeXString = versions [i];
  break;
} catch (ex) {
  // skip;
}
   }
    }
return new ActiveXObject (arguments.callee.activeXString);
   } else {
     throw new Error ("No XHR object available.");
   }
}
 
Usage of XHR
When using the XHR object, the first method to call is open (), which receives three parameters: the type of request to be sent, the URL of the request, and a Boolean value indicating whether to send the request asynchronously.
xhr.open ("get", "example.php", false);
To send a specific request, call the send () method as follows:
xhr.open ("get", "example.php", false);
xhr.send (null);
After the XHR returns from the server, the attributes that change, that is, the attributes that store the corresponding data of the server are:
responseText: The text returned as the response body
responseXML: If the response types are "text / xml" and "application / xml", the XML DOM document holding the response data
status: HTTP status of response
statusText: Description of HTTP status
Before using XHR, you must specify the onreadystatechange event handler to ensure cross-browser compatibility.
var xhr = createXHR ();
xhr.onreadystatechange = function () {
   if (xhr.readyState == "4") {
   if ((xhr.status> = 200 && xhr.status <300) || xhr.status == 304) {
   alert (xhr.responseText);
   } else {
   alert ("Request was unsuccessful:" + xhr.status);
   }
   }
};
xhr.open ("get", "example.text", true);
xhr.send (null);
In addition, you can call the abort () method to cancel the asynchronous request before receiving the response. As follows:
xhr.abort ();
After terminating the request, the XHR object should also be dereferenced. Due to memory reasons, it is not recommended to reuse XHR objects.
 
HTTP header information
XHR objects provide methods for manipulating request headers and responding to header information. By default, when the XHR request is sent, the following header information is also sent:
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: the type of connection between the browser and the server
Cookies: any cookies set on the current page
Host: the domain of the page sending the request
Referer: URI of the page that sent the request
User-Agent: the user agent string of the browser
Use setRequestHeader () method to set custom request header information. This method receives two parameters: the header field name and the header field value. To successfully send request header information, it must be called after calling the open () method and before the send () method. It is recommended to use a custom header name, and some browsers support it or not.
 
POST request
To use post submission, set the header property Content-type. If it is not set, there will be problems such as data cannot be decoded and obtained.
 
XMLHttpRequest Level 2
Not all browsers fully implement the XMLHttpRequest level 2 specification, but all browsers implement some of its specifications.
FormData
It provides traversal for serialized forms and data created in the same format. Refer to the following two examples for usage:
var data = new FormData ();
data.append ("name", "seacean2000");
 
var data = new FormData (document.forms [0]);
It is convenient because it does not need to explicitly set the request header on the XHR object.
 
Timeout setting
The only timeout setting event supported by IE8 + is the ontimeout event of the XHR object. The timeout of the XHR object sets the timeout time in milliseconds. These settings must be after the method is opened and before the send.
// open
xhr.timeout = 1000;
xhr.ontimeout = function () {};
// send
 
overrideMimeType () method
The MIME type used to rewrite the XHR response. It can force the data type returned by the server to those provided for this method. Instructions:
After open, before send.
 
Progress event
There are the following 6 progress events:
loadstart: Triggered when the first byte of the response data is received.
progress: continuous trigger during receiving response data
error: triggered when an error occurs in the request
abort: triggered when the connection is terminated due to the abort () method
load: triggered when complete response data is received
loadend: Triggered after the communication is completed or an error, abort, or load event is triggered.
Now all mainstream browsers support the load event, the first five except IE all support
 
load event
Not all browsers implement the appropriate event object for this event. Here is an example of use:
xhr.onload = function () {
   if ((xhr.status> = 200 && xhr.status <300) || xhr.status == 304) {
   alert (xhr.responseText);
   } else {
   alert ("Request was unsuccessful:" + xhr.status);
   }
}
Put it before the open method.
 
progress event
Mozilla added a new event for XHR, this event will be triggered periodically when the browser receives data. The onprogress event handler will receive an event object whose target property is an XHR object, but contains three additional properties: lengthComputable, position, tatalSize. Where lengthComputable is a Boolean value indicating whether progress information is available, and position is the received bytes Number, totalSize represents the expected number of bytes determined according to the Content-Length response header. With these we can create a progress indicator for the user.
xhr.onprogress = function (event) {
var divStatus = document.getElementById ("status");
if (event.lengthComputable) {
 divStatus.innerHTML = "Received" + event.position + "of" + event.totalSize + "bytes";
}
};
Can only be put before open.
 
Cross-origin resource sharing
A major limitation of Ajax communication through XHR comes from cross-domain security policies. By default, Ajax can only access resources in the same domain as the page that contains it. But sometimes it also requires some cross-domain requests. In order to solve this problem, the current browser uses CORS (Cross-Origin Resource Sharing, cross-domain resource sharing) strategy to achieve. CORS is a W3C working draft that defines how to communicate between the browser and the server when cross-origin resources must be accessed. The basic idea of this strategy is to use a custom HTTP header to allow the browser to communicate with the server to determine the success or failure of the request or response. Note that neither the request nor the response contains cookie information.
 
IE's implementation of CORS
IE8 introduced XDR (XDomainRequest) type, this object is similar to XHR, but can achieve safe and reliable cross-domain communication. The security mechanism of the XDR object partially implements the W3C CORS specification. The following are the differences between XDR and XHR:
The cookie will not be sent with the request or returned with the response
Only the Content-Type field in the request header information can be set
Cannot access response header information
Only GET and POST requests are supported
XDR object usage method: create an instance, call the open method, call the send method. The open method only accepts two parameters: the type of request and the URL. All XDR requests are asynchronous. After the request returns, the load event is triggered, and the response data is saved in the responseText property.
var xdr = new XDomainRequest ();
xdr.onload = function () {
  alert (xdr.responseText);
};
xdr.open ("get", "http://www.somewhere-else.com/page/");
xdr.send (null);
The only information that can be obtained on a cross-domain request is the error itself, so the way to determine the failure of the response is to use the onerror event. To be used before open.
xdr.onerror = function () {
   alert ("an error occurred!");
}
Before the request returns, you can call the abort command abort () method:
xdr.abort (); // The request is terminated
Like XHR, XDR objects also support timeout attributes and ontimeout event handlers.
xdr.timeout = 1000;
xdr.ontimeout = function () {
alert ("late!")
}
Only add these handlers before open.
In order to support post requests, the XDR object provides the contentType attribute, which is used to indicate the format of the sent data: set after open and before send
xdr.contentType = "application / x-www-form-urlencoded";
 
Implementation of CORS in other browsers
Other browsers have implemented native support for CORS through the XMLHttpRequest object. However, the following restrictions apply to cross-domain requests:
You cannot use setRequestHeader () to set a custom header.
Can't accept and send cookies
Calling getAllResponseHeaders () always returns an empty string.
Whether it is a homologous request or a cross-domain request, it is best to use relative URLs for local resources and absolute URLs when accessing remote resources.
 
Preflighted Requests
The transparent server verification mechanism supports developers to use custom headers, methods other than get and post, and different types of theme content. This request uses the OPTIONS method and sends the following headers:
Origi
n: same as simple request
Access-Control-Request-Method: request the method used by itself
Access-Control-Request-Headers: (optional) custom header information, drink more comma separated headers.
After sending the request, the server decides whether to allow this type of request. The server communicates with the browser by sending the following header in response:
Access-Control-Allow-Origin: same as simple request
Access-Control-Allow-Methods: Allowed methods, multiple methods are separated by commas
Access-Control-Allow-Headers: Allowed headers, multiple headers separated by commas
Access-Control-Max-Age: How long should this Preflight request be cached (in seconds)
 
Request with credentials
By setting the withCredentials attribute to true, you can specify that a particular request should send credentials. If the server receives a request with credentials, it will respond with the following HTTP header
Access-Control-Allow-Credentials: true
 
Cross-browser CORS
function createCORSRequest (method, url) {
   var xhr = new XMLHttpRequest ();
   if ("withCredentials" in xhr) {
   xhr.open (method, url, true);
    } else if (typeof XDomainRequest! = "undefined") {
    xhr = new XDomainRequest ();
xhr.open (method, url);
    } else {
   xhr = null;
    }
return xhr;
}
var request = createCORSRequest ("get", "http://somewhere-else.com/page/");
if (request) {
   request.onload = function () {
      //request.responseText
   };
   request.send ();
}
 
Other cross-domain technologies
Image Ping Technology
According to the principle that a web page can load images from any web page without worrying about using cross-domain, we can dynamically create images and use their onload and onerror event handlers to determine whether a response is received.
Dynamic image creation is often used for image ping. Image Ping is a way of simple one-way cross-domain communication with the server. The requested data is sent in the form of a query string, and the ringing can be any content, but it is usually a pixel map or a 204 response. Through the image ping, the browser cannot get any specific data, but by listening to the load and error events, it can know when it was accepted.
var img = new Image ();
img.onload = img.onerror = function () {
  alert ("Done");
};
img.src = "http://ww.example.com/test?name=seacean";
Image Ping is most commonly used to track user clicks on pages or dynamic ad impressions. It has two main disadvantages: it can only send get requests and cannot access the server's response text. Therefore, the image ping can only be used for one-way communication between the browser and the server.
 
JSONP
JSONP is short for JSON with padding. It is a new method of applying json and is very popular in later Web services. JSONP consists of two parts: callback function and data. The callback function is a function that should be called on the page when the response comes. The name of the callback function is generally specified in the request. The data is the json data passed into the callback function. The following is an example of JSONP:
http://freegeoip.net/json/?callback=handleResponse
JSONP is used through the dynamic <script> element. When using it, you can specify a cross-domain URL for the src attribute. The <script> element here has the ability to load resources with other domains without restriction. Because JSONP is effectively JavaScript code, it will be executed immediately after the request is completed, that is, after the JSONP response is loaded on the page.
function handlerResponse (response) {
  alert ("You ‘re at IP address" + response.ip + ", where is in" + response.city + "," + response.region_name);
}
var script = document.createElement ("script");
script.src = "http://freegeoip.net/json/?callback=handlerResponse";
document.body.insertBefore (script, document.body.firstChild);
The advantage of JSONP is that it is easy to use, directly access the response text, and support two-way communication between the browser and the server. The shortcomings of JSONP: It is impossible to determine whether the loaded domain is safe, and it is not easy to determine the failure of the request. In order to avoid these, the current solution of developers is to judge whether a response is received within a specified time.
 
Comet
This is a technology where the server pushes data to the page. Comet allows information to be pushed to the page in near real time, which is ideal for handling sports games and stock quotes. There are two ways to implement Comet: long polling and streaming. Long polling is a version of traditional polling, that is, the browser sends requests to the server regularly to see if there is any data update. Long polling reverses the traditional polling, the page sends a request to the server, and then the server keeps the connection open, knowing that there is data to send. After sending the data, the browser closes the connection and then initiates a new request to the server. This process continues continuously while the page is open. The second popular Comet method is HTTP streaming. The stream uses only one HTTP connection during the entire life cycle of the page. Specifically, the browser sends a request to the server, and then the server keeps the connection open, and then periodically sends data to the browser. The following php script is a common way in a server implemented using streaming:
$ i = 0;
while (true) {
echo "Number is $ i"; // Output data and then refresh the cache
flush ();
sleep (10); // Stop for a few seconds
$ i ++;
}
This code is the key to HTTP streaming.
The following code is a typical code for XHR object to implement HTTP streaming:
function createStreamingClient (url, progress, finished) {
var xhr = new XMLHttpRequest (), received = 0;
 
xhr.open ("get", url, true);
xhr.onreadystatechange = function () {
  var result;
  if (xhr.readyState == 3) {
  result = xhr.responseText.substring (received);
  received + = result.length;
  progress (result);
  } else if (xhr.readyState == 4) {
  finished (xhr.responseText);
  }
};
xhr.send (null);
return xhr;
}
var client = createStreamingCilent ("streaming.php", function (data) {
  alert ("Received:" + data);
  }, function (data) {
  alert ("Done!");
  });
The createStreamingCilent function receives three parameters: the URL to connect to, the function to call when the data is received, and the function to call when the connection is closed.
 
Server send event
SSE (Server-Sent Events) is an API or mode introduced around read-only Comet interaction. The SSE API is used to create a one-way connection to the server through which the server can send any amount of data. The MIME type of the server response must be text / event-stream, and it must be in a format parsed by the Javascript API in the browser. SSE supports short polling, long polling and HTTP streaming, and can automatically determine when to reconnect when disconnected.
SSE API
SSE is for javascript api and it is very similar to other javascript api for passing messages. To schedule a new event stream, create a new EventSource object and pass in an entry point:
var source = new EventSource ("myevents.php");
Note: The URL to be passed in must be the same as the page where the object is created. An instance of EventSource has a readyState property. A value of 0 indicates that it is connecting to the server, a value of 1 indicates that the connection is opened, and a value of 2 indicates that the connection is closed. There are three other events:
open: triggered when a connection is established
message: triggered when a new event is received from the server
error: triggered when the connection cannot be established
The data returned by the server is stored in event.data in a string format. If you want to force an immediate disconnect and no longer reconnect, you can call the close () method.
Event flow
When sending multiple segments of data, separate data from different segments must be separated by line breaks. And you can also add an ID before or after each piece of data to facilitate the splicing of multiple pieces of data. After setting the ID, the EventSource object will track the last triggered event. If the connection is lost, a special HTTP header request called Last-Event-ID is sent to the server so that the server knows which event will be triggered next time. In the event stream of multiple connections, this mechanism ensures that the browser can receive the connected data segments in the correct order.
 
Web Sockets
In js web sockets use a custom protocol. The unencrypted protocol is ws: //; the encrypted protocol is wss: //. Currently the browsers that support it are Safari6 +, Safari5 +, Chrome, and IOS4 +.
Example of creating web sockets:
var sockets = new WebSockets ("ws: //www.example.com/server.php");
Note that you must pass an absolute URL to the WebSockets constructor. The same-origin policy does not apply to it. Whether you can communicate with a specific domain depends entirely on the server.
sockets.close (); // Close
sockets.send ("Hello word"); // Can send string, json format string
The events of sockets are onmessage: the server sends a message to the client, sockets will be triggered; onopen: triggered when the connection is successfully established; onerror: triggered when an error occurs, the connection cannot be continued; onclose: triggered when the connection is closed. The event object in the close event has three additional properties: wasClean, code, reason. The first parameter indicates whether the connection is explicitly closed, boolean. The second is the numeric status code returned by the server, and reason is a string containing the information returned by the server.
 
The Web Sockets protocol is similar to HTTP. Existing servers cannot communicate with Web Sockets. HTTP can meet the requirements. If you only need to request data from the server, then SSE is easier, if the two-way communication Web Sockets is better. When Web Sockets cannot be used, the combination of XHR + SSE can also achieve two-way communication.
 
In terms of AJAX security, the following measures are effective:
Requires SSL connection to access resources that can be requested through XHR
It is required that each request must be accompanied by a verification code calculated by the corresponding algorithm
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.