XMLHttpRequest Level 2 User Guide
XMLHttpRequest is a browser interface that enables Javascript to perform HTTP(S) communication.
At the earliest, Microsoft introduced this interface in IE 5. Because it is so useful, other browsers have imitated the deployment, and the ajax operation was born.
However, this interface has not been standardized, and the implementation of each browser is more or less different. After the concept of HTML 5 was formed, W3C began to consider standardizing this interface. In February 2008, a draft of XMLHttpRequest Level 2 was proposed .
This new version of XMLHttpRequest proposes many useful new features, which will greatly promote Internet innovation. This article will introduce this new version in detail.
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, send an HTTP request to the remote host.
xhr.open(‘GET’,’example.php’);
xhr.send();
Then, it waits for a response from the remote host. At this time, you need to monitor the status changes 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 attributes of the old version of the XMLHttpRequest object:
* xhr.readyState: The state of the XMLHttpRequest object, equal to 4 indicates that the data has been received.
* xhr.status: The status code returned by the server, equal to 200 means everything is normal.
* xhr.responseText: the text data returned by the server
* xhr.responseXML: data in XML format returned by the server
* xhr.statusText: The status text returned by the server.
2. Disadvantages of the old version
The old version of the XMLHttpRequest object has the following disadvantages:
* Only supports the transmission of text data, and cannot be used to read and upload binary files.
* When transmitting and receiving data, there is no progress information, only whether it is completed or not.
* Subject to ” Same Origin Policy ” (Same Origin Policy), data can only be requested from servers of the same domain name.
Three, the function of the new version
The new version of the XMLHttpRequest object has made substantial improvements in response to the shortcomings of the old version.
* You can set the time limit for HTTP requests.
* You can use the FormData object to manage form data.
* You can upload files.
* You can request data under different domain names (cross-domain request).
* You can get the binary data on the server side.
* The progress information of data transmission can be obtained.
Below, I will introduce these new features one by one.
Fourth, the time limit of the HTTP request
Sometimes, the ajax operation is very time-consuming, and it is impossible to predict how much time it will take. If the internet speed is slow, users may have to wait a long time.
The new version of the XMLHttpRequest object adds the timeout attribute, which can set the time limit of the HTTP request.
xhr.timeout = 3000;
In the above statement, the maximum waiting time is set 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 belong to the XDomainRequest object, but Chrome and Safari do not yet support this attribute.
Five, the FormData object
Ajax operations are often used to pass form data. In order to facilitate form processing, HTML 5 has added a new FormData object that can simulate forms.
First, create a new FormData object.
var formData = new FormData();
Then, add form items to it.
formData.append(‘username’,’Zhang San’);
formData.append(‘id’, 123456);
Finally, directly transfer the FormData object. This is exactly the same as submitting a web form.
xhr.send(formData);
The FormData object can also be used to obtain the value of a web 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);
Six, upload files
The new version of XMLHttpRequest object can not only send text messages, but also upload files.
Assuming that files is a “select file” form element (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);
7. Cross-domain resource sharing (CORS)
The new version of the XMLHttpRequest object can send HTTP requests to servers with different domain names. This is called ” Cross-origin resource sharing ” (Cross-origin resource sharing, or CORS).
The premise of using “cross-domain resource sharing” is that the browser must support this function, and the server must agree to this “cross-domain”. If the above conditions can be met, the code writing is exactly the same as the non-cross-domain request.
xhr.open(‘GET’,’http://other.server/and/path/to/script’);
At present, in addition to IE 8 and IE 9, all major browsers support CORS, and IE 10 will also support this feature. For server-side settings, please refer to “Server-Side Access Control” .
8. Receive binary data (Method A: Rewrite MIMEType)
The old version of the XMLHttpRequest object can only retrieve text data from the server (otherwise its name will not start with XML), and the new version can retrieve binary data.
There are two approaches here. The older method 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;
At this time, the browser treats it as text data, so it must be restored to binary data byte by byte.
for (var i = 0, len = binStr.length; i <len; ++i) {
var c = binStr.charCodeAt(i);
var byte = c & 0xff;
}
The bit operation “c & 0xff” in the last line means that among the two bytes of each character, only the last byte is reserved and the previous byte is discarded. The reason is that when the browser interprets the characters, it will automatically interpret the characters into the 0xF700-0xF7ff section of Unicode.
8. Receive binary data (Method B: responseType attribute)
The newer way to retrieve binary data from the server is to use the new responseType attribute. If the server returns text data, the value of this attribute is “TEXT”, which is the default value. Newer browsers also support other values, that is, you can receive data in other formats.
You can set responseType to 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 receiving data, just use the Blob object that comes with the browser.
var blob = new Blob([xhr.response], {type:’image/png’});
Note that xhr.response is read, not xhr.responseText.
You can also set responseType to arraybuffer to pack the binary data in an array.
var xhr = new XMLHttpRequest();
xhr.open(‘GET’,’/path/to/image.png’);
xhr.responseType = “arraybuffer”;
When receiving data, you need to traverse this array.
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 .
Nine, progress information
The new version of the XMLHttpRequest object has a progress event when data is transmitted, which is used to return progress information.
It is divided into two situations: 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 of the progress event.
xhr.onprogress = updateProgress;
xhr.upload.onprogress = updateProgress;
Then, in the callback function, use some 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 bytes that need to be transmitted, and event.loaded is the bytes that have been transmitted. If event.lengthComputable is not true, event.total is equal to 0.
Related to the progress event, there are five other events, you can specify the callback function:
* load event: the transfer was successfully completed.
* abort event: the transmission was cancelled by the user.
* error event: an error occurred during transmission.
* loadstart event: transmission started.
* loadEnd event: the transmission is over, but it is not known whether it succeeded or failed.
10. Reading materials
1. Introduction to XMLHttpRequest Level 2 : A comprehensive introduction to new features.
2. New Tricks in XMLHttpRequest 2 : An introduction to some usages.
3. Using XMLHttpRequest : some advanced usage, mainly for Firefox browser.
4. HTTP Access Control : Overview of CORS.
5. DOM access control using cross-origin resource sharing : 9 kinds of HTTP header information of CORS
6. Server-Side Access Control : Server-side CORS settings.
7. Enable CORS : server-side CORS setting.
(over)