jQuery unveiled: the XMLHttpRequest object

jQuery handles the XMLHttpRequest object this way:


// Create the request object; Microsoft failed to properly
  // implement the XMLHttpRequest in IE7 (can't request local files),
  // so we use the ActiveXObject when it is available
  // This function can be overriden by calling jQuery.ajaxSetup
  xhr: window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject) ?
   function() {
    return new window.XMLHttpRequest();
   } :
   function() {
    try {
     return new window.ActiveXObject("Microsoft.XMLHTTP");
    } catch(e) {}
   },
  accepts: {
   xml: "application/xml, text/xml",
   html: "text/html",
   script: "text/javascript, application/javascript",
   json: "application/json, text/javascript",
   text: "text/plain",
   _default: "*/*"
  }

The XHR object is created via the xhr() method. Then jQuery uses an object literal to store all accepted content types. However, the xhr() method sometimes causes the infamous Automation server can't create object in Internet Explorer 8. This is due to a wrong configuration on the client machine. Simply put, a user may have installed IE8 without updating his/her operating system with the recent library versions. The solution is simple: if you stumble on this error, use a custom method to create an instance of the XHR object. Then retrieve the responseXML or responseText properties and work with them.

Leave a Reply

Note: Only a member of this blog may post a comment.