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 trialPaul Otieno
6,035 PointsgetJSON
I still don't understand the getJSON and why it is used. ANy body?
2 Answers
gregsmith5
32,615 Points$.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
9,474 PointsWow, 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.