What is the getJSON() method in jQuery?

Overview

The getJSON() method in jQuery fetches JSON data from a server using the HTTP GET method.

Syntax

$.getJSON(url, data, function());

Parameters

This method accepts the following parameters.

  • url: This is the URL on which the request is to be made.
  • data: It specifies some additional data that can be sent to the server. It is optional.
  • function(): This is a callback function that is invoked when the request is completed.

Return value

This method returns an object of the XMLHttpRequest type.

Example

Let’s look at an example of the getJSON() method in the code snippet below:

jQuery getJSON() example

Explanation

In the HTML tab:

  • Line 4: We import the jQuery script.
  • Line 7: We create a button Fetch Data.
  • Line 8: We create a div content.

In the JavaScript tab:

  • Line 3: We attach the click() method on the Fetch Data button.
  • Line 4: We use the getJSON() method to get data from this URL.
  • Lines 4-9: We add a callback function to iterate through the response and append the data in the div content.

Output

If the request is successful, the callback function will be invoked, and the data will be appended in the div content.

Free Resources