if (!window.XMLHttpRequest) { window.XMLHttpRequest = function() { return new ActiveXObject('Microsoft.XMLHTTP'); } }
This hack defines a function called XMLHttpRequest if XMLHttpRequest doesn't exist natively on the browser.
With this method, you can make AJAX calls with 'new XMLHttpRequest()' even on IE 6 or 5.5.
var ajax_call = new XMLHttpRequest(); ...
UPDATE : Thanks to comments on Ajaxian, I added the "window." prefix to the declaration of the XMLHttpRequest function in order to work properly on IE 6 and not redefineing the XHR native object on IE 7.
5 comments:
I'm no AJAX expert, but is this a simple, elegant and genious as it looks? Why hasn't this been done before, or has it? If it hasn't a lot of people should be saying "d'oh!" right now :)
Does this break IE7's implementation by re-writing? I'm sorry I haven't tested directly to see; just thought I'd ask.
Could this not be taken a step further and done like:
XMLHttpRequest = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : XMLHttpRequest;
Or even shorter and be:
XMLHttpRequest = XMLHttpRequest || new ActiveXObject('Microsoft.XMLHTTP');
jt, yes it does on IE 7. If not enabling ActiveX on IE 7 is a concern for you, then don't use that code, otherwise, you can use it since ActiveX are of course still part of IE 7.
travis, you cannot do that. The aim here is to define once for all the XMlHttpRequest function. In your example, you have a function on one hand (XMLHttpRequest) and a pointer to an instance of an ActiveX object (new ActiveXObject('Microsoft.XMLHTTP')) on the other hand. That's not compatible.
But what happens if none exist ?
This case is quite rare, but exists.
Post a Comment