Reputation: 1242
I'm confused about the "clean" way to call $.getJSON
.
According to the documentation, the synopsis is:
jQuery.getJSON( url [, data ] [, success ] )
where data
is "a plain object or string that is sent to the server with the request", and success
is "a callback function that is executed if the request succeeds".
In my experience, the data
argument is often not needed in practice, in which case I call $.getJSON
as
$.getJSON( some_url, {}, function(response) { /* do something */ });
That is, I simply pass an empty object as data
. However, I've also seen people use
$.getJSON( some_url, function(response) { /* do something */ });
This is confusing, since it looks like the callback function is being passed as the data
object. Yet it seems to work just fine.
How come this works? Is jQuery "clever" enough to understand the second syntax, even though it doesn't strictly correspond to the specification? Is there effectively some difference in what happens in those two calls? Between the two, is there a preferred way?
Upvotes: 3
Views: 341
Reputation: 385144
Is jQuery "clever" enough to understand the second syntax,
Yes; there is code inside getJSON
to detect the types of its arguments and sort it out that way.
even though it doesn't strictly correspond to the specification
It does. The synopsis you quoted explicitly says exactly that! Square brackets ([]
) in synopses indicate optional arguments. In this case, both arguments are independently optional: you may provide either, or both, or neither.
Is there effectively some difference in what happens in those two calls?
No.
Between the two, is there a preferred way?
No.
Upvotes: 4
Reputation: 11431
The best way I have found to use $.getJSON
without any parameters is like this
$.getJSON('path/to/json.json')
.done(function(response) {
console.log(response);
});
Using deferred's is preferable to using callbacks in almost all circumstances.
This question is a particular favorite of mine to explain why you should choose the deferred syntax -> Asynchronous JavaScript - Callbacks vs Deferred/Promise
Upvotes: 3