RESTful calls via JavaScript

I’ve been doing a lot more front-end work with JavaScript lately and have needed to make calls to RESTful APIs. One of my complaints with JavaScript is that it feels like there is not a standard way of doing things. One can always do things the plain old JavaScript way or one can use one of the many frameworks that exist. This post focuses on the plain vanilla way to use JavaScript to access a RESTful web service API. The following is a sample function that makes a POST call:

RESTService.prototype.doPost = function(url, data, successHandler, errorHandler)
{
    var http = new XMLHttpRequest();

    http.open("POST", url, true);
    http.setRequestHeader("accept", "application/json");
    http.setRequestHeader("content-type", "application/json;charset=UTF-8");

    http.onreadystatechange = function()
    {
        if(http.readyState == 4)
	{
	    if(http.status == 200)
	    {
                successHandler({});
	    }
            else
            {
                errorHandler({});
            }
	}
    };
    http.send(JSON.stringify(data));
};

To change what type of call just change the “POST” to “GET” etc.