Obtain the JSON

Use an API named XMLHttpRequest (XHR) to obtain the JSON. This is a very useful JavaScript object to make network requests to retrieve resources from a server via JavaScript. You can update small content. There’s no need to reload the entire page. More responsive web pages now!

Obtain the JSON

  • Store the URL of the JSON you want to retrieve in a variable. Add the following at the bottom of your JavaScript code:
var requestURL = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';
  • Create a new request object instance from the XMLHttpRequest constructor, using the new keyword. Add the following below your last line:
var request = new XMLHttpRequest();
  • Open a new request using the open() method. Add this:
request.open('GET', requestURL);

This takes at least two parameters. Other option is to use the two mandatory ones for this simple example:

– The HTTP method to use when making the network request. GET is fine.
– The URL to make the request to.  This is the URL of the JSON file that is stored earlier.

  • Set the responseType to JSON, so that XHR knows that the server will be returning JSON and that this should be converted behind the scenes into a JavaScript object. Add the following two lines. Then send the request with the send() method:
request.responseType = 'json';
  • Wait for the response to return from the server and deal with it. Add the following code below your previous code:
request.onload = function() {
  var superHeroes = request.response;

Here you are storing the response to our request (available in the response property) in a variable called superHeroes. This variable will now contain the JavaScript object based on the JSON.




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s