Saturday, November 11, 2006

Which function to get an XMLHttpRequest object ?

Ajax is "quite old" but I've not found any crossbrowser clean or standard way to create and return the correct XMLHttpRequest.

I wrote a standard crossbrowser function in my italian Ajax Guide (http://javascript.html.it/guide/leggi/95/guida-ajax/) but someone, every day, try to discard that function or to create a "new way" to get that object.

My opinion is this one:
- You don't need any conditional comment, these aren't a good code practice
- You don't need any evil eval function ... You can do your check without problems
- You don't need any try catch, first because they're not compatible with old browsers, second because You can simply check browser version and then choose the correct ActiveX, if it's necessary


Then, if You're looking for a simple, fast and cross browser way to get XMLHttpRequest You could just use this function:


function xhr(){ // webreflection.blogspot.com
var xhr = null,
b = navigator.userAgent;
if(window.XMLHttpRequest)
xhr = new XMLHttpRequest();
else if(!/MSIE 4/i.test(b)) {
if(/MSIE 5/i.test(b))
xhr = new ActiveXObject("Microsoft.XMLHTTP");
else
xhr = new ActiveXObject("Msxml2.XMLHTTP");
};
return xhr;
};


Every compatible browser, FF 1+, Opera 8+, Safari 2+, KDE 3.4+, IE 5+, will get a valid XMLHttpRequest while every other browser, for example IE4, will recieve a null value.
Then You can simply verify if client browser support Ajax request using a sintax like this one:

var ajax = xhr();
if(ajax)
// do every async interaction ...


That's all, I hope this will be helpful :)

No comments:

Post a Comment