Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best method of Instantiating an XMLHttpRequest object

What is the best method for creating an XMLHttpRequest object?

It should work in all capable browsers.

like image 350
user51886 Avatar asked Jan 06 '09 02:01

user51886


People also ask

What is the correct way of creating XMLHttpRequest object in Javascript?

Create a new XMLHttpRequest object let xhr = new XMLHttpRequest(); // 2. Configure it: GET-request for the URL /article/.../load xhr. open('GET', '/article/xmlhttprequest/example/load'); // 3. Send the request over the network xhr.

Why do we use the XMLHttpRequest object in AJAX?

XMLHttpRequest (XHR) objects are used to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in AJAX programming.


2 Answers

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;
}
like image 71
Jonathan Lonowski Avatar answered Oct 19 '22 22:10

Jonathan Lonowski


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();
like image 29
user50612 Avatar answered Oct 20 '22 00:10

user50612