asynchronously get json response in javascript

In modern web development, it is common to fetch data from a server using an asynchronous JavaScript request. Here is an example of how to make an asynchronous request to get JSON data using the XMLHttpRequest object.

index.tsx
// make an asynchronous request to JSON endpoint
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/my-json-endpoint');

xhr.onload = () => {
  // parse JSON response
  const response = JSON.parse(xhr.responseText);
  console.log(response);
};

xhr.onerror = () => {
  console.error('Error making request');
};

xhr.send();
344 chars
16 lines

In this example, we create a new instance of XMLHttpRequest and open a GET request to the specified endpoint. We then set up the onload function to handle the response by parsing the JSON into a JavaScript object and logging it to the console.

If an error occurs during the request, the onerror function will be called, and we can handle that however we want. Finally, we send the request using xhr.send().

gistlibby LogSnag