Best method of Instantiating an XMLHttpRequest object Best method of Instantiating an XMLHttpRequest object ajax ajax

Best method of Instantiating an XMLHttpRequest object


For a library-less solution, you can emulate Prototype's use of Try.these fairly easily:

function newAjax() {    try { return new XMLHttpRequest();                    } catch(){}    try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(){}    try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(){}    try { return new ActiveXObject('Msxml2.XMLHTTP');     } catch(){}    try { return new ActiveXObject('Microsoft.XMLHTTP');  } catch(){}    return false;}


Here's a useful link and some code (should cover all bases)

http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx

        var request = null;        function InitAJAX()        {            var objxml = null;            var ProgID = ["Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.3.0", "Microsoft.XMLHTTP"];                        try            {                objxml = new XMLHttpRequest();            }            catch(e)            {                                for (var i = 0; i < ProgID.length; i++)                {                    try                    {                        objxml = new ActiveXObject(ProgID[i]);                    }                    catch(e)                    {                                                continue;                    }                }            }            return objxml;                    }        request = InitAJAX();


Use jQuery (or a similar JavaScript library). It takes care of the cross-browser compatibility issues of things like making Ajax calls.

For example, using the jQuery Ajax call:

$.ajax({    url: 'document.xml',    type: 'GET',    dataType: 'xml',    timeout: 1000,    error: function(){        alert('Error loading XML document');    },    success: function(xml){        // do something with xml    }});