jQuery.getJSON() Example

If you are creating an Ajaxy web application jQuery offers a few great methods to help you out. In this tutorial I will demonstrate one of those; the getJSON() function. I’ll create a simple example of how this wonderful powerful, yet beautifully simple function can be used.

jQuery’s getJSON() function was created to retrieve JSON-encoded data from a server. It’s actually just shorthand for the ajax() function.

I’ll start by saying that I personally love JSON and generally prefer it to XML when transferring data with Ajax requests. By nature its structure is generally less bloated than XML, therefore reducing data transfer bandwidth. It’s easy to use. And it translates directly to Javascript objects.

OK, so on to the example. Download the minified version of the jQuery library at jQuery.com. Save the file in your web root as “jquery.js”.

The markup above gives us a very simple web page with the jQuery file referenced, a section of Javascript in the “head” where we can write our Javascript code, and a button element. We also have a textarea where we will show the results of our requests. Let’s add a click event handler to the button that will make our Ajax request using the “getJSON” function. Put the following in the head script.

A few things happen in the code above. First, we use the ready() function, much like we might use the document.onload event handler. Inside this handler we add a click event handler to the button. When the button is clicked we make a call to getJSON(). There are a couple options with the parameters of getJSON(). In this example we define the name of the request web resource/page. Next we define an object (using JSON) with data we want to give the backend as a filter for our results. The third parameter defines our success handler. We expect the resulting data to be in a certain format as you can see in the code above. If we have the proper format then our example should create a new line for each “person” received in the request result.

Note that this function uses the jQuery.ajax() method, and will always convert any data sent into a querystring (GET), rather than a POST.