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.
Copy Code code as follows:
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:
Copy Code code as follows:
* 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.
Copy Code code as follows:
* 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.
Copy Code code as follows:
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.
Copy Code code as follows:
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);
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.
Copy Code code as follows:
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.
Copy Code code as follows:
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.
Copy Code code as follows:
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.
var blob = new Blob ([Xhr.response], {type: ' Image/png '});
Note that it is reading xhr.response, not xhr.responsetext.
You can also set the Responsetype as Arraybuffer and put binary data in an array.
Copy Code code as follows:
var xhr = new XMLHttpRequest ();
Xhr.open (' Get ', '/path/to/image.png ');
Xhr.responsetype = "Arraybuffer";
When you receive data, you need to traverse this array.
Copy Code code as follows:
var arraybuffer = Xhr.response;
if (Arraybuffer) {
var ByteArray = new Uint8array (arraybuffer);
for (var i = 0; i < bytearray.bytelength; i++) {
Do something
}
}
For more detailed discussion, see Sending and receiving Binary Data.
Ix. Progress Information
A new version of the XMLHttpRequest object that transmits data with a progress event to return progress information.
It is divided into two situations of uploading and downloading. 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.
Copy Code code as follows:
xhr.onprogress = UpdateProgress;
xhr.upload.onprogress = UpdateProgress;
Then, in the callback function, use some of the properties of this event.
Copy Code code as follows:
function UpdateProgress (event) {
if (event.lengthcomputable) {
var percentcomplete = event.loaded/event.total;
}
}
In the code above, Event.total is the total byte that needs to be transmitted, event.loaded is the byte that has been transferred. If event.lengthcomputable is not true, then event.total equals 0.
Related to the progress event, there are five other events that can specify the callback function individually:
* Load Event: Transfer completed successfully.
* Abort event: The transfer was canceled by the user.
* Error Event: Errors occurred in transport.
* Loadstart Event: Transmission started.
* Loadend event: Transmission ends, but no success or failure is known.
Ten, reading materials
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 Firefox browsers.
4. HTTP Access control:cors Overview.
5.9 Kinds of HTTP header information for DOM access control using Cross-origin resource Sharing:cors
6. Server-side Access Control: Server-side cors settings.
7. Enable CORS: Service-side CORS settings.