Saturday, February 9, 2008

Native (W3C) XMLHttpRequest for IE6 and earlier browsers

With IE7 implementing XMLHttpRequest as a native JavaScript Object, the need to fork JavaScript for XMLHttpRequest is now limited to IE6 and earlier major browsers.

Here is my wrapper for IE6 and lower browsers so you can use the XMLHttpRequest syntax in those browsers also.

/**
* Emulate window.XMLHttpRequest in IE6-
*/
if (!window.XMLHttpRequest) {
 var ms_xhr_ver = false;
 window.XMLHttpRequest = function() {
  if (ms_xhr_ver) return new ActiveXObject(ms_xhr_ver);
  var xhr = false;
  var versions = [
  "Msxml2.XMLHTTP.7.0", 
  "Msxml2.XMLHTTP.6.0", 
  "Msxml2.XMLHTTP.5.0", 
  "Msxml2.XMLHTTP.4.0", 
  "MSXML2.XMLHTTP.3.0", 
  "MSXML2.XMLHTTP",
  "Microsoft.XMLHTTP"];
  var n = versions.length;
  for (var i = 0; i <  n; i++) {
   try {
    if (xhr = new ActiveXObject(versions[i])) {
     ms_xhr_ver = versions[i];
     break;
    }
   } catch (e) { /* try next */ }
  }
  return xhr;
 };
}

Here is some example usage:

/**
* Example usage of native XHR in IE6
*/
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() { 
 if (xhr.readyState == 4) {
  if (xhr.status == 200) {
   alert(xhr.responseText);
  }
 }
};
xhr.open('get', '/2008/02/native-w3c-xmlhttprequest-for-ie6-and.html');
xhr.send('');

Try It

You'll notice that you can use the same syntax in all major browsers, Firefox, IE6, IE7, Safari etc. There is not branching of code once you have emulated native XMLHttpRequest for IE6 and earlier browsers. This can be a good base to either make XMLHttpRequest requests directly, or to build your XMLHttpRequest library.

While I'm on the topic, I'd like to point out a major flaw in some popular XMLHttpRequest libraries. They wrap the ActiveX based XHR of IE6 and earlier before wrapping the native XMLHttpRequest. This will make IE7 use the older version of XMLHttpRequest.

Next I think I'll blog about cross-domain XMLHttpRequest.

No comments: