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 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.
function () { if (xhr.readystate = = 4 && xhr.status = =) { 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: The text data returned by the server * xhr.responsexml: The server returns the data 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. /// new version of the XMLHttpRequest object, added the Timeout property, can set the time limit for HTTP requests. xhr.timeout =n; // 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. 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. varFormData =NewFormData (); //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. varform = document.getElementById (' MyForm '); varFormData =NewFormData (form); Formdata.append (' Secret ', ' 123456 ');//Add a form itemXhr.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 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. varBinstr =Xhr.responsetext; //because of this, the browser considers it as text data, so it must be reverted to binary data in bytes. for(vari = 0, len = binstr.length; i < Len; ++i) {varc =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.
varnew XMLHttpRequest (); Xhr.open (' GET ', '/path/to/image.png '= ' blob ';
When you receive data, use the Blob object that comes with your browser.
var 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 New XMLHttpRequest (); Xhr.open (' GET ', '/path/to/image.png '= "Arraybuffer";
This array needs to be traversed when the data is received.
var arrayBuffer = xhr.response; if (arrayBuffer) { varnew Uint8array (arrayBuffer); for (var i = 0; i < bytearray.bytelength; i++) { // do something c18/>} }
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; = 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.
XMLHttpRequest Level 2 User Guide