csdnceshi62 2012-01-12 18:25 采纳率: 100%
浏览 218
已采纳

Ajax 处理持续响应:"success:"vs"。 "搞定"?

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?

转载于:https://stackoverflow.com/questions/8840257/jquery-ajax-handling-continue-responses-success-vs-done

  • 写回答

2条回答 默认 最新

  • 7*4 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单