三生石@ 2012-01-12 18:25 采纳率: 100%
浏览 196

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

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.

From the synopsis from the jQuery documentation we get:

.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.

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?

  • 写回答

2条回答 默认 最新

  • weixin_33711647 2013-11-06 14:11
    关注

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

    For example, success:

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

    For example, 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.

    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 $.ajax call 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_get definition (being sure to return a promise or at least a done method, in the case of the example above). All the other references throughout the app can remain the same.

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

    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 $.Deferred here: http://api.jquery.com/category/deferred-object/

    NOTE: As of jQuery 1.8, pipe has been deprecated in favor of using then in exactly the same way.

    评论

报告相同问题?

悬赏问题

  • ¥15 CSS实现渐隐虚线框
  • ¥15 有没有帮写代码做实验仿真的
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真