HTTP GET request in JavaScript?

mclaughlinj picture mclaughlinj · Oct 29, 2008 · Viewed 1.9M times · Source

I need to do an HTTP GET request in JavaScript. What's the best way to do that?

I need to do this in a Mac OS X dashcode widget.

Answer

Joan picture Joan · Oct 27, 2010

Browsers (and Dashcode) provide an XMLHttpRequest object which can be used to make HTTP requests from JavaScript:

function httpGet(theUrl)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
    xmlHttp.send( null );
    return xmlHttp.responseText;
}

However, synchronous requests are discouraged and will generate a warning along the lines of:

Note: Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), synchronous requests on the main thread have been deprecated due to the negative effects to the user experience.

You should make an asynchronous request and handle the response inside an event handler.

function httpGetAsync(theUrl, callback)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() { 
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            callback(xmlHttp.responseText);
    }
    xmlHttp.open("GET", theUrl, true); // true for asynchronous 
    xmlHttp.send(null);
}