alexis
01-09-2007, 07:22 PM
Older versions of Internet Explorer consider XMLHttpRequest as an ActiveX object while other browsers, such as Firefox, Safari and Opera, include it as a native Javascript object. That's why you need to test certain conditions before creating a new instance.
These are some of the most used alternatives:
var xmlHttp;
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
function createXHR() {
var xhr;
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xhr = false;
}
}
if (!xhr && typeof XMLHttpRequest != 'undefined') {
xhr = new XMLHttpRequest();
}
return xhr;
}
Internet Explorer 7 now includes XMLHttpRequest as a native object and that's why this alternative calls it first, something you may also do with try/catch:
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
jQuery (http://jquery.com/) uses a slightly different method:
if (jQuery.browser.msie && typeof XMLHttpRequest == "undefined")
XMLHttpRequest = function(){
return new ActiveXObject("Microsoft.XMLHTTP");
}
and then:
var xml = new XMLHttpRequest();
I think the try/catch degrades better and cover more ground.
How do you create your XMLHttpRequest objects and why?
These are some of the most used alternatives:
var xmlHttp;
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
function createXHR() {
var xhr;
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xhr = false;
}
}
if (!xhr && typeof XMLHttpRequest != 'undefined') {
xhr = new XMLHttpRequest();
}
return xhr;
}
Internet Explorer 7 now includes XMLHttpRequest as a native object and that's why this alternative calls it first, something you may also do with try/catch:
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
jQuery (http://jquery.com/) uses a slightly different method:
if (jQuery.browser.msie && typeof XMLHttpRequest == "undefined")
XMLHttpRequest = function(){
return new ActiveXObject("Microsoft.XMLHTTP");
}
and then:
var xml = new XMLHttpRequest();
I think the try/catch degrades better and cover more ground.
How do you create your XMLHttpRequest objects and why?
