New ways I: fetch
TL; DR I would recommend this method until you need to send synchronous requests or support older browsers.
As long as your request is asynchronous, you can use the Fetch API to send HTTP requests. The fetch API works with promises , which is a good way to handle asynchronous workflows in JavaScript. With this approach, you use fetch() to send the request and ResponseBody.json() to parse the response:
fetch(url) .then(function(response) { return response.json(); }) .then(function(jsonResponse) {
Compatibility: The Fetch API is not supported by IE11, as well as Edge 12 and 13. However, there are polyfills .
New Ways II: responseType
As Londeren wrote in his answer , new browsers allow the use of responseType to determine the expected response format. Then, the analyzed response data can be obtained through the response property:
var req = new XMLHttpRequest(); req.responseType = 'json'; req.open('GET', url, true); req.onload = function() { var jsonResponse = req.response;
Compatibility: responseType = 'json' not supported by IE11.
Classic way
The standard XMLHttpRequest does not have the responseJSON property, only responseText and responseXML . As long as bit-by-bit really answers some JSON to your request, responseText should contain the JSON code as text, so all you have to do is JSON.parse() it with JSON.parse() :
var req = new XMLHttpRequest(); req.overrideMimeType("application/json"); req.open('GET', url, true); req.onload = function() { var jsonResponse = JSON.parse(req.responseText);
Compatibility. This approach should work with any browser that supports XMLHttpRequest and JSON .
JSONHttpRequest
If you prefer to use responseJSON but want a lighter solution than jQuery, you can check out my JSONHttpRequest. It works just like regular XMLHttpRequest, but also provides a responseJSON property. All you need to change in your code will be the first line:
var req = new JSONHttpRequest();
JSONHttpRequest also provides functionality for easily sending JavaScript objects as JSON. More information and code can be found here: http://pixelsvsbytes.com/2011/12/teach-your-xmlhttprequest-some-json/ .
Full disclosure: I am the owner of Pixels | Bytes. I think my script is a good solution to the problem, so I posted it here. Please leave a comment if you want me to delete the link.