Tuesday 9 June 2015

Using XMLHttpRequest in JavaScript


XMLHttpRequest


 XMLHttpRequest makes sending HTTP requests very easy. You simply create an instance of the object, open a URL, and send the request. The HTTP status of the result, as well as the result's contents, are available in the request object when the transaction is completed. This page outlines some of the common and even slightly obscure use cases for this powerful JavaScript object.


Sample code:


function sendRequest(url,callback,postData) {
            var req = createXMLHTTPObject();
            if (!req) return;
            var method = (postData) ? "POST" : "GET";
            req.open(method,url,true);
            req.setRequestHeader('User-Agent','XMLHTTP/1.0');
            if (postData)
                        req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
            req.onreadystatechange = function () {
                        if (req.readyState != 4) return;
                        if (req.status != 200 && req.status != 304) {
//                                  alert('HTTP error ' + req.status);
                                    return;
                        }
                        callback(req);
            }
            if (req.readyState == 4) return;
            req.send(postData);
}

var XMLHttpFactories = [
            function () {return new XMLHttpRequest()},
            function () {return new ActiveXObject("Msxml2.XMLHTTP")},
            function () {return new ActiveXObject("Msxml3.XMLHTTP")},
            function () {return new ActiveXObject("Microsoft.XMLHTTP")}
];

function createXMLHTTPObject() {
            var xmlhttp = false;
            for (var i=0;i<XMLHttpFactories.length;i++) {
                        try {
                                    xmlhttp = XMLHttpFactories[i]();
                        }
                        catch (e) {
                                    continue;
                        }
                        break;
            }
            return xmlhttp;
}

sendRequest('file.txt',handleRequest);

Now the file file.txt is fetched, and when that's done the functionhandleRequest() is called. This function receives the XMLHttpRequest object as an argument, which I traditionally call req (though, of course, you can use any variable name you like). Typically, this function reads out the responseXML orresponseText and does something with it.


function handleRequest(req) {
            var writeroot = [some element];
            writeroot.innerHTML = req.responseText;
}

This function creates a new XMLHttpRequest object for every request you make. In simple cases such as this site, where every page fetches only three to five files, I don't mind creating three to five objects. In more complex sites, however, where any page can make an arbitrary amount of requests, it's probably better to write a function that reuses existing XMLHttpRequest objects.


No comments:

Post a Comment