我已经使用jQuery和AJAX工作了几个星期了,我看到了两种不同的方式来“继续”脚本一旦调用已经做出:success:和.done。

从jQuery文档的简介中我们得到:

.done():描述:在解析Deferred对象时添加要调用的处理程序。 success:(.ajax()选项):请求成功时调用的函数。

因此,两者都在AJAX调用完成/解析之后执行一些操作。我可以随意使用其中一种吗?两者的区别是什么?什么时候用一种代替另一种?


当前回答

success是jQuery中成功回调的传统名称,定义为ajax调用中的一个选项。然而,自从实现了$。延迟回调和更复杂的回调,done是实现成功回调的首选方式,因为它可以在任何延迟上调用。

例如,成功:

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

例如,done:

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

The nice thing about done is that the return value of $.ajax is 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 $.ajax itself and bind your callbacks with done, fail, then, or whatever. Note that always is a callback that will run whether the request succeeds or fails. done will only be triggered on success.

例如:

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
});

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

使用$还可以做更多(更酷的)事情。延迟的,其中之一是使用管道触发服务器报告的错误的失败,即使$。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
});

阅读更多关于$的信息。此处延迟:http://api.jquery.com/category/deferred-object/

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

其他回答

success是jQuery中成功回调的传统名称,定义为ajax调用中的一个选项。然而,自从实现了$。延迟回调和更复杂的回调,done是实现成功回调的首选方式,因为它可以在任何延迟上调用。

例如,成功:

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

例如,done:

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

The nice thing about done is that the return value of $.ajax is 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 $.ajax itself and bind your callbacks with done, fail, then, or whatever. Note that always is a callback that will run whether the request succeeds or fails. done will only be triggered on success.

例如:

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
});

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

使用$还可以做更多(更酷的)事情。延迟的,其中之一是使用管道触发服务器报告的错误的失败,即使$。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
});

阅读更多关于$的信息。此处延迟:http://api.jquery.com/category/deferred-object/

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

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

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

来自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 object for 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:

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

成功回调选项的另一种构造,请参阅deferred.done()了解实现细节。

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

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

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

(在jQuery 1.6中添加) 作为完全回调选项的另一种构造,.always()方法替代了已弃用的.complete()方法。

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

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

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

弃用通知:jqXHR.success()、jqXHR.error()和jqXHR.complete()回调函数在jQuery 3.0被移除。你可以使用 jqXHR.done()、jqXHR.fail()和jqXHR.always()取而代之。