Correct way to call $ .getJSON?
I am confused about the "clean" way of calling $.getJSON
.
According to the documentation , a quick overview:
jQuery.getJSON( url [, data ] [, success ] )
where data
is "a simple object or string that is sent to the server with a request" and success
is a callback function that is executed if the request succeeds. "
In my experience the argument is data
often unnecessary in practice, in which case I call $.getJSON
as
$.getJSON( some_url, {}, function(response) { /* do something */ });
That is, I just pass an empty object as data
. However, I've also seen people use
$.getJSON( some_url, function(response) { /* do something */ });
This is confusing as it looks like the callback function is being passed as an object data
. However, it looks like everything is working fine.
How it works? Is jQuery smart enough to understand the second syntax, even though it is strictly out of specification? Is there any difference in what happens in these two calls? Is there a preferred way in between?
source to share
Is jQuery smart to understand the second syntax,
Yes; getJSON
there is code inside to detect the types of its arguments and sort it that way.
although this is strictly not spec
This is true. The synopsis you quoted directly speaks of this! Square brackets ( []
) in bulletins indicate optional arguments. In this case, both arguments are, independently of each other, optional: you can specify either, or both, or not.
Is there any difference in what happens in these two calls?
Not.
Between the two, is there a preferred way?
Not.
source to share
The best way I've found using $.getJSON
without any parameters is like this:
$.getJSON('path/to/json.json')
.done(function(response) {
console.log(response);
});
Using deferred calls is preferable to using callbacks in almost all circumstances.
This question is my favorite explanation of why you should choose deferred syntax -> Asynchronous JavaScript - callbacks and deferral / promise
source to share