XMLHttpRequest Level 2 User Guide

Source: Internet
Author: User
Tags vcard

XMLHttpRequest Level 2 User Guide

Nanyi

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

At first, Microsoft introduced this interface in IE 5. Because it is too useful, other browsers mimic the deployment, and Ajax operations are thus born.

However, this interface has not been standardized, the implementation of each browser is more or less a little different. After the concept of HTML 5 was formed, the consortium began to consider standardizing the interface. A draft of XMLHttpRequest Level 2 was proposed in February 2008.

This new version of XMLHttpRequest, which presents a number of useful new features, will greatly contribute to internet innovation. This article gives a detailed introduction to this new version.

One, the old version of the XMLHttpRequest object

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

First, create a new instance of XMLHttpRequest.

var xhr = new XMLHttpRequest ();

Then, an HTTP request is made to the remote host.

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

Xhr.send ();

Next, wait for the remote host to respond. You need to monitor the state change of the XMLHttpRequest object and specify the callback function.

Xhr.onreadystatechange = function () {

if (xhr.readystate = = 4 && xhr.status = = 200) {

alert (Xhr.responsetext);

} else {

alert (Xhr.statustext);

}

};

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

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

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

* Xhr.responsetext: Text data returned by the server

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

* Xhr.statustext: The status text returned by the server.

Ii. disadvantages of the old version

The old version of the XMLHttpRequest object has several drawbacks:

* Only text data transfer is supported and cannot be used to read and upload binary files.

* When transmitting and receiving data, there is no progress information and can only prompt for completion.

* Subject to "Same domain Restrictions" (same Origin Policy), data can only be requested from servers of the same domain name.

Third, 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 under different domain names (cross-domain requests).

* Server-side binary data can be obtained.

* The progress information of the data transfer can be obtained.

Here, I'll cover these new features.

Iv. time limit for HTTP requests

Sometimes, Ajax operations are time-consuming and unpredictable, and they don't know how long it will take. If the network speed is slow, users may have to wait a long time.

The new version of the XMLHttpRequest object, which adds the Timeout property, allows you to set the time limit for HTTP requests.

Xhr.timeout = 3000;

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

Xhr.ontimeout = function (event) {

Alert (' Request timed out! ‘);

}

Currently, Opera, Firefox and IE 10 support this attribute, ie 8 and IE 9 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 has a new Formdata object that can be used to simulate a form.

First, create a new Formdata object.

var formData = new FormData ();

Then, add the form items to it.

Formdata.append (' username ', ' Zhang San ');

Formdata.append (' id ', 123456);

Finally, transfer the Formdata object directly. This is exactly the same as the effect of submitting Web Forms.

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 form Item

Xhr.open (' POST ', form.action);

Xhr.send (FormData);

Vi. Uploading Files

The new XMLHttpRequest object can not only send text messages, but also upload files.

Assume that files is a form element (input[type= "file") that "selects Files", and 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 issue HTTP requests to servers of different domain names. This is called "cross-domain resource sharing" (cross-origin resource sharing, or cors).

The premise of using cross-domain resource sharing is that the browser must support this feature, and the server side must agree to this "cross-domain". If the above conditions are met, the code is written exactly like a request that does not cross a domain.

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

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

Eight, receive binary data (method A: Overwrite mimetype)

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

There are two ways of doing this. The older approach is to rewrite 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 ");

Then, use the ResponseText property to receive the binary data returned by the server.

var binstr = Xhr.responsetext;

Because of this, the browser considers it as text data, so it must be reverted to binary data in bytes.

for (var i = 0, len = binstr.length; i < Len; ++i) {

var c = binstr.charcodeat (i);

var byte = c & 0xFF;

}

The bitwise operation of the last line, "C & 0xFF", represents two bytes per character, leaving only the latter byte, discarding the previous byte. The reason is that when the browser interprets the characters, the characters are automatically interpreted into the Unicode 0xf700-0xf7ff section.

Eight, receive binary data (method B:responsetype property)

Retrieving binary data from the server, the newer method 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, which means that you can receive data in other formats.

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

var xhr = new XMLHttpRequest ();

Xhr.open (' GET ', '/path/to/image.png ');

Xhr.responsetype = ' blob ';

When you receive data, use the Blob object that comes with your browser.

var blob = new Blob ([Xhr.response], {type: ' Image/png '});

Note that it is read xhr.response, not xhr.responsetext.

You can also set the Responsetype to Arraybuffer and put binary data in an array.

var xhr = new XMLHttpRequest ();

Xhr.open (' GET ', '/path/to/image.png ');

Xhr.responsetype = "Arraybuffer";

This array needs to be traversed when the data is received.

var arrayBuffer = Xhr.response;

if (ArrayBuffer) {

var byteArray = new Uint8array (arrayBuffer);

for (var i = 0; i < bytearray.bytelength; i++) {

Do something

}
}

For a more detailed discussion, see Sending and receiving Binary Data.

Ix. Progress Information

The new version of the XMLHttpRequest object, when transmitting data, has a progress event that is used to return the progress information.

It is divided into two scenarios: Upload and download. The downloaded progress event belongs to the XMLHttpRequest object, and the uploaded progress event belongs to the Xmlhttprequest.upload object.

We first define the callback function for the progress event.

xhr.onprogress = UpdateProgress;

xhr.upload.onprogress = UpdateProgress;

Then, in the callback function, use some of the properties of this event.

function UpdateProgress (event) {

if (event.lengthcomputable) {

var percentcomplete = event.loaded/event.total;

}

}

In the above code, Event.total is the total byte that needs to be transmitted, and event.loaded is the byte that has been transferred. If event.lengthcomputable is not true, then event.total equals 0.

In connection with the progress event, there are five other events that can be assigned to a callback function:

* Load Event: Transfer completed successfully.

* Abort event: The transfer was canceled by the user.

* Error Event: A failure occurred in the transmission.

* Loadstart Event: Transfer started.

* Loadend Event: Transfer ended, but did not know success or failure.

Ten, reading material

1. Introduction to XMLHttpRequest Level 2: A comprehensive introduction to the new features.

2. New Tricks in XMLHttpRequest 2: Introduction to some usages.

3. Using XMLHttpRequest: Some advanced usage, mainly for the Firefox browser.

4. HTTP Access control:cors Overview.

5. DOM access control using Cross-origin resource Sharing:cors 9 kinds of HTTP header information

6. Server-side Access Control: Server-side cors settings.

7. Enable cors: Server-side cors settings.

Finish

XMLHttpRequest Level 2 User Guide

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.