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 trialSunny Singh
1,148 PointsHow do I know and decide when I should be using a $.getJSON() or $.getJSONP() or $.ajax() method for requests?
Having confusion understanding which method is right to use when?
2 Answers
LaVaughn Haynes
12,397 Points$.getJSON() is shorthand usage of $.ajax(). For example:
$.getJSON()
is equal to
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
Use getJSON if you need to fetch a json file from your site.
You are not allowed to just load json from other peoples sites for security reasons, so if you need to do that then you will probably need to specify that you want jsonp (JSON with Padding) and the site will have to return the json data in a wrapper. I'm not aware of a $.getJSONP function, but you can specify that you expect jsonp data returned using either $.getJSON() or $.ajax().
Use $.ajax() if you you need to specify some custom configuration that you don't get with the shorthand. The jQuery API will give you all of the details and options available http://api.jquery.com/jquery.ajax/
Ryan Chatterton
5,914 Pointsbuilding on @LaVaughn Haynes answer there is not a $.getJSONP() function but in your $.ajax you will have a option to call a jsonp service.
$.ajax({
url: "http://notmydomain.com/api",
jsonp: "callback",
datatype: "jsonp",
data: {q: "select stuff", format: "json"},
success: function( data) {
console.log(data) ;
}
});
you would jsonp mainly when you are doing across domain calls, but this is tricky as it's a main tactic for cross site scripting attacks.
LaVaughn Haynes
12,397 PointsLaVaughn Haynes
12,397 PointsI've also heard some people say that they prefer to use $.ajax because $.getJSON is just going to call $.ajax anyway, but this level of speed optimization may not not necessarily worth sacrificing the convenience of using the shorthand for a lot of people. http://jonraasch.com/blog/10-advanced-jquery-performance-tuning-tips-from-paul-irish