Export (0) Print
Expand All

XMLHttpRequest enhancements

Internet Explorer 10 and Windows Store apps using JavaScript introduce several enhancements to the XMLHttpRequest object to provide greater support for emerging standards and to more easily support common developer scenarios. These include the following:

  • Downloading and uploading binary files, such as images, video, and audio without the use of plug-ins.
  • Download streaming of multimedia content without the use of plug-ins.
  • Improved insight into the status of XMLHttpRequest operations.
  • Improved interoperability with other browsers.

These changes are described in more detail in the following sections.

Binary Object upload and download

Internet Explorer 10 extends XMLHttpRequest to support binary data. This is accomplished, in part, by adding support for the Blob interface of the File API specification.

When the responseType property of an XMLHttpRequest object is set to "blob", the data associated with the request is treated as binary data. This affects the value of the response property for download requests (for instance, GET).

The following example shows how to use XMLHttpRequest to download an image to a blob object and then assign the result to an image element on the webpage.


var req = new XMLHttpReqest();
xhr.open("GET", "download?name=" + name, true);
xhr.responseType = "blob";
xhr.onreadystatechange = function () {
  if (xhr.readyState == xhr.DONE) {
    var blob = xhr.reponse;
    var image = document.getElementById("my-image");
    image.addEventListener("load", function (evt) {
      URL.revokeObjectURL(evt.target.src);
    }
    image.src = URL.createObjectURL(blob);
  }
}
xhr.send();

When the responseType property is set to "ms-stream" for download requests, content can be handled on the fly, as shown in the following example.


var xhr = new XMLHttpReqest();
xhr.open("GET", "download?name=" + name, true);
xhr.responseType = "ms-stream";
xhr.onreadystatechange = function () {
  if (xhr.readyState == xhr.LOADING) {
    var stream = xhr.reponse;
    var video = document.getElementById("my-video");
    video.addEventListener("loadeddata", function (evt) {
      URL.revokeObjectURL(evt.target.src);
    }
    video.src = URL.createObjectURL(stream);
  }
}
xhr.send();

Comet streaming support

Internet Explorer 10 supports multipart HTTP streaming (also known as Comet streaming) by allowing the responseText property to be read while the response to an XMLHttpRequest request is loading, as shown in the following example:


xhr.open("GET", url);
xhr.timeout = timeout;
xhr.onreadystatechange = function() {
  if (this.readyState >= 3 && this.status == 200) {
    var content = this.responseText;
    handleContent(content);
  }
}
xhr.send();

In earlier versions of Windows Internet Explorer, the responseText property can be read only when the readyState property is set to done.

Be aware that the responseText property returns the full value of the response read to date. If you wish to handle individual packets of the response as they are received, you can use the progress event (described in the next section) or track the length of responseText in each iteration of the readyStateChange event, as shown in the following example:


xhr.open("GET", url);
xhr.timeout = timeout;
xhr.onreadystatechange = function() {
  if (typeof this.index == "undefined")
    this.index = 0;
    
  if (this.readyState >= 3 && this.status == 200) {
    var content = this.responseText;
    handleContent( content.substring(this.index) )
    this.index = content.length;
  }
}
xhr.send();

Enhanced event support

Internet Explorer 10 extends the XMLHttpRequest object to support the following events specified in the XMLHttpRequest Level 2 specification:

EventDescription

loadstart

Fires when the request starts.

progress

Fires at server-defined intervals while the request is sending or receiving data.

abort

Fires when the request is canceled, for instance, when the abort() method is called.

error

Fires when the request fails.

load

Fires when the request is successfully completed.

timeout

Fires when an author-specified period of time has elapsed

loadend

Fires when the request completes, either successfully or unsuccessfully.

 

Event handling for the XMLHttpRequest object follows the models specified in the DOM Events Level 3 specification and the Progress Events specification, as shown in the following example.


var xhr = new XMLHttpRequest();
var url = "some-url";

xhr.timeout = 5000;
xhr.addEventListener("timeout", handleTimeout(evt), false);

xhr.onprogress = function(evt) {
  handleEvent("data: " + this.responseText);
  // Calculate progress 
  var str = "";
  if (evt.lengthComputable) {
    var percent = 100 * evt.loaded / evt.total;
    str = percent + "%. Current total size: " + this.responseText.length);
  } else {
    str = "Progress unknown. Current total size: " + this.responseText.length;
  }
  updateProgress(str);
}
xhr.open("GET", url);
xhr.send();

Cross-Origin Resource Sharing (CORS) for XMLHttpRequest

Internet Explorer 10 adds support for Cross-Origin Resource Sharing (CORS) with respect to the XMLHttpRequest (XHR) object. Defined in the Cross-Origin Resource Sharing specification, CORS uses HTTP headers to enable cross-domain web requests that are normally restricted by the same-site origin policy.

By default, the same-site origin policy prevents websites from requesting resources from servers on other domains. However, browsers that support CORS for XMLHttpRequest (XHR) requests can access resources from other domains if the appropriate administrator chooses to allow such requests.

When a webpage makes an XHR request,Internet Explorer sends an origin header to the target server; the header contains the protocol scheme of the request (either http:// or https://) and the hostname for the webpage making the request. If the target server approves the request, it returns an Access-Control-Allow-Origin header and the request is allowed to proceed.

XMLHttpRequest objects now support a withCredentials property, which allows XHR requests to include authorization mechanisms. For more information, see the XMLHttpRequest Level 2 specification.

The withCredentials property can be used to detect CORS support, as shown in the following example.


var url = "http://contoso.com/services/"
if( window.XMLHttpRequest ) {
  var oReq = new XMLHttpRequest();
  if( oReq.withCredentials == true ) {
    oReq.open("GET", url, true);
    oReq.onload = handleResponse();
    oReq.send( null );
  } else {
  // CORS not support.  Handle fallback
  }
} else { 
  // XMLHttpRequest not supported; handle fallback
}

API Reference

XMLHTTPRequest (XHR) and AJAX Support

Samples and tutorials

About Native XMLHTTP
AJAX - Connectivity Enhancements in Windows Internet Explorer 8
Introducing AJAX Navigations
Introducing Cross-domain Request (XDR)
XMLHttpRequest Enhancements in Windows Internet Explorer 8

Internet Explorer Test Drive demos

Cross-Site Upload

IEBlog posts

XMLHttpRequest responseXML in IE10 Release Preview
CORS for XHR in IE10
Asynchronous Programming in JavaScript with “Promises”
ActiveX Filtering for Developers

Specification

XMLHttpRequest Level 2

 

 

Show:
© 2014 Microsoft