Get JSON data with JavaScript XMLHttpRequest | Plantpot

Get JSON Data with JavaScript XMLHttpRequest

Web Dev
Sponsored links

In this article, I will introduce how to get JSON data with JavaScript XMLHttpRequest.

What is JSON?

JSON is an abbreviation for "JavaScript Object Notation" and is one of the data formats of character strings.
Since it is a character string, it is easy to use for exchanging data over the network.
Therefore, it is often used for communication when using services on the Internet.

First of all, please recognize it as a data format that has almost the same syntax as JavaScript.

Below is an example of json data.

{
  "name": "Plantpot",
  "age": 20,
  "language": ["HTML", "CSS", "JavaScript"]
}
Sponsored links

What is XMLHttpRequest?

The XMLHttpRequest (XHR) object is one of the Web APIs used to interact with the server.
You can use the XMLHttpRequest (XHR) object to get the data without refreshing the entire page.

The syntax for creating an XMLHttpRequest object is:

let xhr = new XMLHttpRequest();
Sponsored links

Get JSON data with XMLHttpRequest

The following is a simple sample to get JSON data and display it.

JSON
{
  "name": "Plantpot",
  "age": 20,
  "language": ["HTML", "CSS", "JavaScript"]
}
JavaScript
//Create an XMLHttpRequest object
let xhr = new XMLHttpRequest();

//Initializes a request
xhr.open('GET', "https://plantpot.works/v1/json/0123abcd");

//The process fires when an XMLHttpRequest transaction is successfully completed
xhr.onload = () => {
  let responseJson = JSON.parse(xhr.response);
  console.log(responseJson.name);
  // => "Plantpot" 
}

//Send the request
xhr.send();