基本的 getJSON 问题——第二个参数似乎总是被忽略

basic getJSON question -- 2nd argument always seems to be ignored

我对 Javascript、Jquery 以及介于两者之间的一切都很陌生。我一直在努力理解 getJSON 函数——文档中说:

jQuery.getJSON( url [, data ] [, success ] )

典型例子:

$.getJSON( "ajax/test.json", function( data ) {
  var items = [];
  $.each( data, function( key, val ) {
    items.push( "<li id='" + key + "'>" + val + "</li>" );
  });

getJSON 调用中的第二个参数在哪里?

似乎 function(data) 正在定义一个在请求成功后调用的函数,这意味着它应该是第三个参数。

但它作为第二个参数传递,直接在 "ajax/test.json" 参数之后。

getJSON是否假设如果只有两个参数,第二个是成功的?

文档中的 [] 表示参数是 可选的

您的示例中省略了 data 参数。因此,第二个参数是 success 函数。

getJSON函数测试第二个参数的类型,确定它是一个函数,并将其用作success函数。

这是getJSON内部的样子:

getJSON: function( url, data, callback ) {
    return jQuery.get( url, data, callback, "json" );
},

下面是 JQuery 包装 GETPOST 请求的方式:

jQuery.each( [ "get", "post" ], function( _i, method ) {
    jQuery[ method ] = function( url, data, callback, type ) {

        // Shift arguments if data argument was omitted
        if ( typeof data === "function" ) {
            type = type || callback;
            callback = data;
            data = undefined;
        }

        // The url can be an options object (which then must have .url)
        return jQuery.ajax( jQuery.extend( {
            url: url,
            type: method,
            dataType: type,
            data: data,
            success: callback
        }, jQuery.isPlainObject( url ) && url ) );
    };
} );

上面的示例来自 github 上的 jquery sources