Forum Moderators: open

Message Too Old, No Replies

XMLHttp

Trying to fail gracefully in old Explorer

         

dcrombie

12:51 pm on Feb 21, 2005 (gmt 0)



I've been doing some work using XMLHttp but the JS code errors in Explorer 5.5 (Windows) and 5.2 (Mac). It seems to work as expected in Explorer 6.0 (Windows). Anyone have an option short of browser-sniffing?!?

var req; 
function loadXMLDoc(url)
{
if(window.XMLHttpRequest) {
// code for Gecko/KHTML browsers
} else if(window.ActiveXObject) {
==> execution gets to here, then errors on next line
if(req = new ActiveXObject("Microsoft.XMLHTTP")) {
// code for Explorer
}
}
}

dcrombie

2:40 pm on Feb 21, 2005 (gmt 0)



Found the solution:

try { 
req = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
req = new ActiveXObject("Msxml2.XMLHTTP");
}

;)

Bernard Marx

3:58 pm on Feb 21, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You could spread the net further:

function getXMLHttp()
{
var xml;
try
{
// Mozilla Browsers
xml = new XMLHttpRequest();
return xml;
}
catch(e){}

// IE Browsers
var progIDs = ["MSXML2.XMLHttp.5.0","MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp","Microsoft.XMLHttp"];
for(var currentProgID = 0;currentProgID < progIDs.length;currentProgID++)
{
try
{
xml = new ActiveXObject(progIDs[currentProgID]);
return xml;
}
catch(e){}
}
}

dcrombie

4:17 pm on Feb 21, 2005 (gmt 0)



Jeepers! I didn't realise it was such a mess - are there actually browsers that only support, for example, "MSXML2.XMLHttp.5.0" and not "MSXML2.XMLHttp" or "Microsoft.XMLHttp"?

I assume "MSXML2.XMLHttp" came first and the numerical suffixes indicate more recent versions (like JavaScript1.2 et. al.)?

Bernard Marx

4:32 pm on Feb 21, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I'm probably more in the dark than you are here. I got that list in the array from a friend. Here's some MS info that might explain it all:
[msdn.microsoft.com...]

dcrombie

5:00 pm on Feb 21, 2005 (gmt 0)



[msdn.microsoft.com...]

Currently, the default XML parser for Internet Explorer is MSXML 2.0 or MSXML 3.0, depending on the version of Internet Explorer. With the help of the xmslinst.exe utility, you can change the default parser to MSXML 2.6 or MSXML 3.0. However, this can often cause unintended side-effects for some applications. Therefore, such a practice is not enabled for MSXML versions 4.0 and later....

I think that means you can leave off the numeric extensions and Explorer will use it's default.

Bernard Marx

5:02 pm on Feb 21, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Ah good stuff. That'll certainly make the code shorter!