Guidelines for the use of XMLHttpRequest level 2

Source: Internet
Author: User
Tags character set http request new features resource time limit

XMLHttpRequest is a browser interface that allows JavaScript to communicate in HTTP (S).

First, Microsoft introduced this interface in IE 5. Because it was so useful, other browsers also imitated the deployment, so the Ajax operation was born.

However, this interface has not been standardized, and each browser's implementation is somewhat different. After the concept of HTML 5 was formed, the consortium began to consider standardizing the interface. In February 2008, a draft of XMLHttpRequest Level 2 was proposed.

The new version of this XMLHttpRequest, which brings up a lot of useful new features, will greatly promote Internet innovation. This article on this new version of the detailed introduction.

First, the old version of the XMLHttpRequest object

Before we introduce the new version, let's review the usage of the old version.

First, create a new instance of XMLHttpRequest.

var xhr = new XMLHttpRequest ();

Then, issue an HTTP request to the remote host.

Xhr.open (' Get ', ' example.php ');

Xhr.send ();

Next, wait for the remote host to respond. This requires monitoring the state changes of the XMLHttpRequest object and specifying the callback function.

Xhr.onreadystatechange = function () {
    
if (xhr.readystate = = 4 && xhr.status =) {
    
alert (xhr.re  Sponsetext);
    
else {
    
alert (xhr.statustext);
    
}
    
};

The code above contains the main properties of the old version XMLHttpRequest object:

* Xhr.readyState:XMLHttpRequest the state of the object, equal to 4 to indicate that the data has been received.

* Xhr.status: The status code returned by the server equals 200 to indicate that everything is OK.

* Xhr.responsetext: Text data returned by the server

* Xhr.responsexml: Data returned by the server in XML format

* Xhr.statustext: Status text returned by the server.

Second, the shortcomings of the old version

The older version of the XMLHttpRequest object has several drawbacks:

* Only support text data transfer, can not be used to read and upload binary files.

* Send and receive data, there is no progress information, can only hint that there is no completion.

* Subject to the "Same domain Limit" (Same Origin Policy), you can request data only to servers of the same domain name.

Three, the new version of the function

The new version of the XMLHttpRequest object, for the shortcomings of the old version, made a significant improvement.

* You can set the time limit for HTTP requests.

* You can use the Formdata object to manage form data.

* Can upload files.

* You can request data from different domain names (cross-domain requests).

* Can get binary data from server side.

* You can obtain progress information on data transfer.

Next, I'll explain these new features.

Iv. time limit for HTTP requests

Sometimes, Ajax operations can be time-consuming and unpredictable in how long it takes. If the internet is slow, the user may have to wait a long time.

The new version of the XMLHttpRequest object, with the addition of the Timeout property, to set the time limit for HTTP requests.

Xhr.timeout = 3000;

The above statement, set the maximum wait time to 3000 milliseconds. After this time limit, the HTTP request is automatically stopped. There is also a timeout event to specify the callback function.

Xhr.ontimeout = function (event) {
    
alert (' Request timeout! ');
    
}

At present, Opera, Firefox and IE 10 support this attribute, ie 8 and IE 9 of this attribute belongs to the Xdomainrequest object, and Chrome and Safari are not supported.

V. Formdata objects

Ajax operations are often used to pass form data. To facilitate form processing, HTML 5 adds a Formdata object that can simulate a form.

First, create a new Formdata object.

var formData = new FormData ();

Then, add a table item for it.

Formdata.append (' username ', ' John ');

Formdata.append (' id ', 123456);

Finally, send the Formdata object directly. This is exactly the same as the effect of submitting a Web form.

Xhr.send (FormData);

The Formdata object can also be used to get the value of a Web page form.

var form = document.getElementById (' MyForm ');
    
var formData = new FormData (form);
    
Formdata.append (' secret ', ' 123456 '); Add a table single
    
xhr.open (' POST ', form.action);
    
Xhr.send (FormData);

Six, upload the file

New XMLHttpRequest object, not only can send text information, can also upload files.

Assuming that the files are a form element of a "Select File" (input[type= "file"]), we load it into the Formdata object.

var formData = new FormData ();
    
for (var i = 0; i < files.length;i++) {
    
formdata.append (' files[] ', files[i]);
    
}

Then, send this Formdata object.

Xhr.send (FormData);

Vii. cross-domain resource sharing (CORS)

A new version of the XMLHttpRequest object that can send HTTP requests to servers of different domain names. This is called "cross-domain resource sharing" (Cross-origin resource sharing, referred to as cors).

The premise of using Cross-domain resource sharing is that browsers must support this feature, and the server side must agree to this "Cross-domain". If the above conditions are met, the code will be written in exactly the same way as a request that does not cross the domain.

Xhr.open (' Get ', ' http://other.server/and/path/to/script ');

Currently, in addition to IE 8 and IE 9, the mainstream browsers support Cors,ie 10 will also support this feature. Server-side settings, refer to "Server-side Access control."

Viii. receiving binary data (method A: Rewriting mimetype)

Old version of the XMLHttpRequest object, can only retrieve text data from the server (otherwise its name does not use the XML first), the new version can retrieve binary data.

This is divided into two ways. The older approach is to overwrite the mimetype of the data, disguise the binary data returned by the server as text data, and tell the browser that this is a user-defined character set.

Xhr.overridemimetype ("Text/plain; Charset=x-user-defined ");

The ResponseText property is then used to receive the binary data returned by the server.

var binstr = Xhr.responsetext;

Because at this point, the browser as a text data, so it must be a byte to revert to the binary data.

for (var i = 0, len = binstr.length i < len; ++i) {
    
var c = binstr.charcodeat (i);
    
var byte = c & 0xFF;
    
}

The last line of bitwise operations "C & 0xFF", which represents two bytes per character, retains only the latter byte and discards the previous byte. The reason is that when browsers interpret characters, they automatically interpret the characters as Unicode 0xf700-0xf7ff sections.

VIII. Receive binary data (method B:responsetype property)

The newer way to retrieve binary data from the server is to use the new Responsetype property. If the server returns text data, the value of this property is "text", which is the default value. Newer browsers also support other values, that is, you can receive data from other formats.

You can set the Responsetype as a blob, which means that the server returns a binary object.

var xhr = new XMLHttpRequest ();
    
Xhr.open (' Get ', '/path/to/image.png ');
    
Xhr.responsetype = ' blob ';

When you receive data, you can use a Blob object from your browser.

More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/webkf/tools/

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.