jQuery.ajax 处理继续响应:“成功:”与“.done”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8840257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 11:07:32  来源:igfitidea点击:

jQuery.ajax handling continue responses: "success:" vs ".done"?

ajaxjquery

提问by Claudio

I have been working with jQuery and AJAX for a few weeks now and I saw two different ways to 'continue' the script once the call has been made: success:and .done.

我已经使用 jQuery 和 AJAX 工作了几个星期,我看到两种不同的方法在调用后“继续”脚本:success:.done.

From the synopsis from the jQuery documentationwe get:

jQuery 文档的概要我们得到:

.done(): Description: Add handlers to be called when the Deferred object is resolved.

success: (.ajax() option): A function to be called if the request succeeds.

.done(): 描述:添加处理延迟对象时调用的处理程序。

成功:(.ajax() 选项):请求成功时调用的函数。

So, both do something after the AJAX call has been completed/resolved. Can I use one or the other randomly? What is the difference and when one is used instead of the other?

因此,在 AJAX 调用完成/解决后,两者都做一些事情。我可以随意使用一种或另一种吗?有什么区别?何时使用一个而不是另一个?

回答by glortho

successhas been the traditional name of the success callback in jQuery, defined as an option in the ajax call. However, since the implementation of $.Deferredsand more sophisticated callbacks, doneis the preferred way to implement success callbacks, as it can be called on any deferred.

success一直是 jQuery 中成功回调的传统名称,定义为 ajax 调用中的一个选项。但是,由于$.Deferreds和 更复杂的回调的实现,done是实现成功回调的首选方式,因为它可以在任何deferred.

For example, success:

例如,成功:

$.ajax({
  url: '/',
  success: function(data) {}
});

For example, done:

例如,完成:

$.ajax({url: '/'}).done(function(data) {});

The nice thing about doneis that the return value of $.ajaxis now a deferred promise that can be bound to anywhere else in your application. So let's say you want to make this ajax call from a few different places. Rather than passing in your success function as an option to the function that makes this ajax call, you can just have the function return $.ajaxitself and bind your callbacks with done, fail, then, or whatever. Note that alwaysis a callback that will run whether the request succeeds or fails. donewill only be triggered on success.

好的一点done是, 的返回值$.ajax现在是一个延迟承诺,可以绑定到应用程序中的任何其他地方。因此,假设您想从几个不同的地方进行这个 ajax 调用。而不是你的成功传递函数作为一个选项,以使这个Ajax调用的功能,你可以有函数返回$.ajax本身并绑定你的回调donefailthen,或什么的。请注意,这always是一个无论请求成功还是失败都会运行的回调。done只会在成功时触发。

For example:

例如:

function xhr_get(url) {

  return $.ajax({
    url: url,
    type: 'get',
    dataType: 'json',
    beforeSend: showLoadingImgFn
  })
  .always(function() {
    // remove loading image maybe
  })
  .fail(function() {
    // handle request failures
  });

}

xhr_get('/index').done(function(data) {
  // do stuff with index data
});

xhr_get('/id').done(function(data) {
  // do stuff with id data
});

An important benefit of this in terms of maintainability is that you've wrapped your ajax mechanism in an application-specific function. If you decide you need your $.ajaxcall to operate differently in the future, or you use a different ajax method, or you move away from jQuery, you only have to change the xhr_getdefinition (being sure to return a promise or at least a donemethod, in the case of the example above). All the other references throughout the app can remain the same.

就可维护性而言,这样做的一个重要好处是您已将 ajax 机制包装在特定于应用程序的函数中。如果您决定$.ajax将来需要以不同的方式调用调用,或者使用不同的 ajax 方法,或者远离 jQuery,则只需更改xhr_get定义(确保返回一个 promise 或至少一个done方法,在上面例子的情况)。整个应用程序中的所有其他引用都可以保持不变。

There are many more (much cooler) things you can do with $.Deferred, one of which is to use pipeto trigger a failure on an error reported by the server, even when the $.ajaxrequest itself succeeds. For example:

您可以使用更多(更酷的)事情做$.Deferred,其中之一是pipe用于触发服务器报告的错误失败,即使$.ajax请求本身成功。例如:

function xhr_get(url) {

  return $.ajax({
    url: url,
    type: 'get',
    dataType: 'json'
  })
  .pipe(function(data) {
    return data.responseCode != 200 ?
      $.Deferred().reject( data ) :
      data;
  })
  .fail(function(data) {
    if ( data.responseCode )
      console.log( data.responseCode );
  });
}

xhr_get('/index').done(function(data) {
  // will not run if json returned from ajax has responseCode other than 200
});

Read more about $.Deferredhere: http://api.jquery.com/category/deferred-object/

$.Deferred在此处阅读更多信息:http: //api.jquery.com/category/deferred-object/

NOTE: As of jQuery 1.8, pipehas been deprecated in favor of using thenin exactly the same way.

注意:从 jQuery 1.8 开始,pipe已弃用,以支持then以完全相同的方式使用。

回答by AmirHossein Manian

If you need async: falsein your ajax, you should use successinstead of .done. Else you better to use .done. This is from jQuery official site:

如果你需要async: false在你的 ajax 中,你应该使用success而不是.done. 否则你最好使用.done. 这是来自jQuery 官方网站

As of jQuery 1.8,the use of async: falsewith jqXHR ($.Deferred) is deprecated; you mustuse the success/error/completecallback options instead ofthe corresponding methods of the jqXHR object such as jqXHR.done().

从 jQuery 1.8 开始,不推荐使用带有 jqXHR ($.Deferred)的async: false;您必须使用成功/错误/完成回调选项而不是jqXHR 对象的相应方法,例如jqXHR.done()

回答by Sasmit

From JQuery Documentation

来自JQuery 文档

The jqXHR objects returned by $.ajax()as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred objectfor more information). These methods take one or more function arguments that are called when the $.ajax()request terminates. This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.) Available Promise methods of the jqXHR object include:

$.ajax()jQuery 1.5 开始返回的 jqXHR 对象实现了 Promise 接口,为它们提供了 Promise 的所有属性、方法和行为(有关更多信息,请参阅延迟对象)。这些方法采用一个或多个在$.ajax()请求终止时调用的函数参数。这允许您在单个请求上分配多个回调,甚至在请求可能完成后分配回调。(如果请求已经完成,则立即触发回调。) jqXHR 对象的可用 Promise 方法包括:

jqXHR.done(function( data, textStatus, jqXHR ) {});

An alternative construct to the success callback option, refer to deferred.done()for implementation details.

成功回调选项的替代构造,请参阅deferred.done()有关实现的详细信息。

jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});

An alternative construct to the error callback option, the .fail()method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.

错误回调选项的替代构造,该.fail()方法替换了已弃用的 .error() 方法。有关实现细节,请参阅 deferred.fail()。

jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { }); 

(added in jQuery 1.6) An alternative construct to the complete callback option, the .always()method replaces the deprecated .complete()method.

(在 jQuery 1.6 中添加)完整回调选项的替代构造,该.always()方法替换了已弃用的.complete()方法。

In response to a successful request, the function's arguments are the same as those of .done(): data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail(): the jqXHR object, textStatus, and errorThrown. Refer to deferred.always()for implementation details.

为了响应成功的请求,该函数的参数与以下参数相同.done():data、textStatus 和 jqXHR 对象。对于失败的请求,参数与以下参数相同.fail():jqXHR 对象、textStatus 和 errorThrown。参考deferred.always()实现细节。

jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {});

Incorporates the functionality of the .done()and .fail()methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then()for implementation details.

结合了.done().fail()方法的功能,允许(从 jQuery 1.8 开始)操作底层 Promise。.then()有关实现细节,请参阅延迟。

Deprecation Notice:The jqXHR.success(), jqXHR.error(), and jqXHR.complete()callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always()instead.

弃用注意:所述的jqXHR.success()jqXHR.error()jqXHR.complete()回调除去的jQuery 3.0。您可以使用 jqXHR.done()jqXHR.fail()jqXHR.always()来代替。