How to create HTTP GET request in JavaScript?

Mahabubur Rahman
0


Browser provide an XMLHttpRequest object which can be used to make HTTP requests from JavaScript. You can create a function as following - 

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 show a warning along its line.


You should make an asynchronous request and handle the response in an event handler. So the code will as bellow - 

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);
}








Post a Comment

0Comments
Post a Comment (0)