【问题标题】:Why is this $.getJSON call in the jquery documentation correct?为什么 jquery 文档中的 $.getJSON 调用正确?
【发布时间】:2013-02-03 18:12:15
【问题描述】:

我对 jQuery 文档有点困惑。我在看this page describing $.getJSON。代码示例是:

$.getJSON('ajax/test.json', function(data) {
  var items = [];

  $.each(data, function(key, val) {
    items.push('<li id="' + key + '">' + val + '</li>');
  });

  $('<ul/>', {
    'class': 'my-new-list',
    html: items.join('')
  }).appendTo('body');
});

但是方法签名是jQuery.getJSON( url [, data ] [, success(data, textStatus, jqXHR) ] ),其中data是发送给服务器的对象,success是JSON请求返回成功时调用的方法。

那么为什么示例代码有效?它似乎跳过了第二个参数。我本来希望正确的代码是:

$.getJSON('ajax/test.json', {}, function(data) {
// and then the same from here

我知道方括号表示[, data][, success] 参数是可选的,但我想我不明白javascript 如何处理可变数量的参数。

感谢您的宝贵时间。

【问题讨论】:

  • 我认为它会检查参数类型,如果是function会变成success,否则会变成data,但是我不知道jQuery是如何做到的
  • jquery 函数使用它独特的解析方法,它不仅检查参数,还检查参数计数和类型。
  • 为什么不看看源代码? .getJSON()(或 here 获取完整源代码)
  • 是的,我的猜测是正确的 =D

标签: javascript jquery optional optional-arguments


【解决方案1】:

参数数量:

arguments.length

然后他们检查参数的类型并确定您提供了哪些参数。

例如:

if(typeof arguments[0] === 'string') // first parameter is a string so it must be url
if(typeof arguments[1] === 'object') // second parameter is an object so it must be data passed to server
if(typeof arguments[2] === 'function') // third parameter is a function so it must be callback

【讨论】:

    【解决方案2】:

    jQuery 源码里面:

    // shift arguments if data argument was omitted
            if ( jQuery.isFunction( data ) ) {
                type = type || callback;
                callback = data;
                data = undefined;
            }
    

    原来如此

    【讨论】:

    • 很高兴它是特定于 jQuery 的,而不是我还没有遇到的 javascript 的魔法法则!
    猜你喜欢
    • 2015-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多