调用 $.getJSON 的正确方法?
Proper way of calling $.getJSON?
我对 "clean" 调用 $.getJSON
的方式感到困惑。
根据the documentation,大纲是:
jQuery.getJSON( url [, data ] [, success ] )
其中 data
是 "a plain object or string that is sent to the server with the request",success
是 "a callback function that is executed if the request succeeds"。
根据我的经验,实践中通常不需要 data
参数,在这种情况下我将 $.getJSON
称为
$.getJSON( some_url, {}, function(response) { /* do something */ });
也就是说,我只是将一个空对象作为data
传递。但是,我也看到人们使用
$.getJSON( some_url, function(response) { /* do something */ });
这令人困惑,因为看起来回调函数是作为 data
对象传递的。然而它似乎工作得很好。
这怎么行? jQuery "clever" 是否足以理解第二种语法,即使它并不严格符合规范?在这两个电话中发生的事情实际上有什么不同吗?两者之间,有更优的方式吗?
我发现在没有任何参数的情况下使用 $.getJSON
的最佳方法是这样的
$.getJSON('path/to/json.json')
.done(function(response) {
console.log(response);
});
在几乎所有情况下,使用 deferred 都优于使用回调。
我特别喜欢这个问题来解释为什么你应该选择延迟语法 -> Asynchronous JavaScript - Callbacks vs Deferred/Promise
Is jQuery "clever" enough to understand the second syntax,
是; getJSON
中有代码可以检测其参数的类型并以这种方式对其进行排序。
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?
没有
我对 "clean" 调用 $.getJSON
的方式感到困惑。
根据the documentation,大纲是:
jQuery.getJSON( url [, data ] [, success ] )
其中 data
是 "a plain object or string that is sent to the server with the request",success
是 "a callback function that is executed if the request succeeds"。
根据我的经验,实践中通常不需要 data
参数,在这种情况下我将 $.getJSON
称为
$.getJSON( some_url, {}, function(response) { /* do something */ });
也就是说,我只是将一个空对象作为data
传递。但是,我也看到人们使用
$.getJSON( some_url, function(response) { /* do something */ });
这令人困惑,因为看起来回调函数是作为 data
对象传递的。然而它似乎工作得很好。
这怎么行? jQuery "clever" 是否足以理解第二种语法,即使它并不严格符合规范?在这两个电话中发生的事情实际上有什么不同吗?两者之间,有更优的方式吗?
我发现在没有任何参数的情况下使用 $.getJSON
的最佳方法是这样的
$.getJSON('path/to/json.json')
.done(function(response) {
console.log(response);
});
在几乎所有情况下,使用 deferred 都优于使用回调。
我特别喜欢这个问题来解释为什么你应该选择延迟语法 -> Asynchronous JavaScript - Callbacks vs Deferred/Promise
Is jQuery "clever" enough to understand the second syntax,
是; getJSON
中有代码可以检测其参数的类型并以这种方式对其进行排序。
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?
没有