Date: 2009-07-31 05:02:17 Created: 2009-07-30 07:18:12
To start myself off the right way, I have done something extremely common: created a function to get XMLHttpRequest objects from browsers. Wikipedia has example code (check the external) to get uniform behaviour out of old Internet Explorer versions and all other browsers, I have simply changed it around and expanded it in a way which looks a bit nicer to me. The repeated try-catches seemed ugly, so I made a loop instead, and I define the XMLHttpRequest object once I found a version which works, instead of having the object looking for the right version each time it is invoked.
So, getRequest simply tries to create a new XMLHttpRequest object. If that produces an exception, it checks if XMLHttpRequest is undefined. (Yes, one should normally do comparisons like this using === to avoid type coercion, but as this is dealing with old browsers I feel safer keeping the example's coercing ==.) If so, it does the standard IE handling - define XMLHttpRequest as a function which returns the correct ActiveXObject. Finally, if something else goes wrong (as noted, I have no real idea what that could be), I throw an error.
After the first run, the XMLHttpRequest object will be defined and work for all browsers, so only the first line in the topmost try will be executed, which feels nice and clean.
I have even tried it on Internet Explorer 5, and it actually worked after a few embarassing fixes (like not actually returning the object and things like that).
So, mission accomplished for today: I sat down and created something common and simple, I did it in my own way and enjoyed the process.
getRequest is shown below, click here to get it in a js-file (right/control-clicking is probably best).
function getRequest() {
try {
return new XMLHttpRequest();
} catch(e) {
if (typeof(XMLHttpRequest) == "undefined") {
var versions = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.5.0',
'Msxml2.XMLHTTP.4.0', 'Msxml2.XMLHTTP.3.0', 'Msxml2.XMLHTTP',
'Microsoft.XMLHTTP'];
var numVersions = versions.length;
for(var i = 0; i < numVersions; i ) {
try {
new ActiveXObject(versions[i]);
XMLHttpRequest = function() {
return new ActiveXObject(versions[i]);
}
return new XMLHttpRequest();
} catch(ignore) {}
}
throw new Error(42, "This browser does not support XMLHttpRequest.");
} else { // No idea what might happen to get us here, so better throw the error.
throw e;
}
}
}