Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.