为什么jQuery成功回调有时有3个参数,有时只有1个

Why does the jQuery success callback sometimes have 3 parameters and sometimes have only 1?

本文关键字:1个 参数 3个 回调 jQuery 为什么 成功      更新时间:2024-05-26

似乎有两种方法可以为jQuery构建成功回调,一种形式有3个参数,另一种形式只有1个参数。以下哪一种是正确的,为什么两种形式都出现?

查看文档中的success函数:http://api.jquery.com/jquery.ajax/

Function( Anything data, String textStatus, jqXHR jqXHR ) A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object.

因此,success函数可以采用3个参数:返回的数据、响应的状态和XHR对象。大多数情况下,您只需要第一个参数。

也许您想知道为什么这两种ajax使用都有效?

$.post(url, callback-when-success);
$.post(url, data-to-be-posted, callback-when-success, server-return-datatype);

让我们来看看$.post() 的实现(源代码)

jQuery.post = function( url, data, callback, type ) {
    /** the trick is right here ! **/
    // shift arguments if data argument was omitted
    if ( jQuery.isFunction( data ) ) {
        type = type || callback;
        callback = data;
        data = undefined;
    }
    return jQuery.ajax({
        url: url,
        type: method,
        dataType: type,
        data: data,
        success: callback
    });
    };
});

事实上,$.post()总是需要四个参数,如果省略了data-to-be-posted(应该在第二个位置)参数,并且success-callback位于第二位置,那么data将被指定为undefined,而success-callback仍然是success-callback

thendone方法不关心回调有多少参数。jQuery Promise1可以用多个参数进行解析,所有这些参数都将传递给回调。你真正想要/需要使用其中的哪些以及有多少是你的事。

一些例子:

  • 动画队列CCD_ 13通过单个参数即元素集合来解析
  • CCD_ 14通过CCD_
  • 内部使用的Animation承诺使用两个参数进行解析
  • $.ajax承诺用success, statusText, jqXHR参数解决
  • $.when(promise1, promise2, promise3, …)承诺通过任意多个参数来解决
  • promise.then(function() { return … })承诺使用单个值解析

1:请注意,几乎所有其他promise库都只为单个值设置promise,请参阅这里的示例