Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript AJAX Basics (retiring) jQuery and AJAX The Office Status Project Revisited

getJSON

I still don't understand the getJSON and why it is used. ANy body?

2 Answers

$.getJSON() is a shorthand method included with jQuery, which means it includes certain behaviors by default that you would have to code manually otherwise. It is used to call a resource pointed to by a URL and request a response in JSON format. In plain JavaScript, you'd have to do something like this

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       // Action to be performed when the document is read;
    }
};
xhttp.open("GET", "http://some.url", true);
xhttp.send();

jQuery shortens this with the $.ajax() method:

$.ajax({
  dataType: "json",
  url: "http://some.url",
  data: data
}).done(successCallback);

People write AJAX requests to retrieve JSON documents so often that jQuery created $.getJSON which does everything the above code does, but with one line

$.getJSON("http://some.url", data).done(successCallback);
S Ananda
S Ananda
9,474 Points

Wow, this is very helpful to be able to see just how much jQuery can shorten code. This is exciting to me after months of writing vanilla JS to wrap my head around it in at least some form. Now I'm finding I understand and can implement things like AJAX/JSON and jQuery with a better understanding of what is going on "under the hood." I was so lost the first time I tried to learn jQuery, before understanding anything about JS.