【问题标题】:Why does the jQuery success callback sometimes have 3 parameters and sometimes have only 1?为什么jQuery成功回调有时有3个参数,有时只有1个?
【发布时间】:2015-03-03 21:18:53
【问题描述】:

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

【问题讨论】:

    标签: javascript jquery ajax promise


    【解决方案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对象。大多数时候,您只需要第一个参数。

    【讨论】:

      【解决方案2】:

      也许您想知道为什么这两种使用 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 放在第二个位置,那么@ 987654327@ 将被分配为 undefined,而 success-callback 仍将是 success-callback

      【讨论】:

        【解决方案3】:

        thendone 方法不关心你的回调有多少参数。 jQuery Promise1 可以使用多个参数进行解析,所有这些参数都将传递给您的回调。您实际想要/需要使用哪些和多少是您的业务。

        一些例子:

        • 动画队列.promise 使用一个参数解析,元素集合。
        • @987654324@.promise 使用 jQuery 函数解析
        • 内部使用的 Animation 承诺使用两个参数解析
        • $.ajax 承诺使用 success, statusText, jqXHR 参数解析
        • @987654326@(promise1, promise2, promise3, …) 承诺可使用任意多个参数解析
        • promise.then(function() { return … }) 承诺使用单个 值解析

        1:请注意,几乎所有其他 Promise 库都只为单个值提供 Promise,例如参见 here

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多