How to use JSON to do an HTTP Request

Use JSON to perform an HTTP request to retrieve data from a remote location.

JSON is most commonly used in asynchronous HTTP requests. This is where an application pulls data from another application via an HTTP request on the web.

Basic Example

In this example, we'll use artists.txt, which contains the following data:

Below is a sample HTML page that retrieves that JSON data via HTTP, and uses JavaScript to wrap it in HTML tags and output it to the HTML document. I've provided plenty of comments in order to explain what each part of the code is doing.

Try it

XMLHttpRequest is an API that provides scripted client functionality for transferring data between a client and a server. It allows you to get data from an external URL without having to refresh the page. For example, a user could click a button that results in a small part of the page updating, rather than the whole page.

XMLHttpRequest is used heavily in Ajax. Despite its name, it can be used to fetch any type of data — not just XML.

XMLHttpRequest includes a number of methods and attributes. In the above example, we use open() to initialize the request, and send() to send the request