The questions:

  1. Should we change our coding as suggested below?
  2. Is there a difference between .done() & success:, .fail() & error: and .always() & complete:?

The preamble:

I was putting together a jQuery.ajax call, which I have done successfully in the past too. Something like this:

    $.ajax(
    {
        url: someUrl,
        type: 'POST',
        data: someData,
        datatype: 'json',
        success: function (data) { someSuccessFunction(data); },
        error: function (jqXHR, textStatus, errorThrown) { someErrorFunction(); }
    });

While taking a quick look at some documentation, I came across a reference stating that The success, error and complete callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

We should therefore start coding something like this instead:

$.ajax( "example.php" )
    .done(function (data) { someSuccessFunction(data); })
    .fail(function (jqXHR, textStatus, errorThrown) { someErrorFunction(); })
    .always(function() { alert("complete"); });

推荐答案

Well there is no advantage of doing that in that particular situation.

The point of the .done() .fail() .always() methods is that you can

  1. 连接多个处理程序
  2. 在任何地方都可以这样做,而不仅仅是在拨打$.ajax的时候

If you are at the $.ajax call site only attaching single handlers then those advantages don't really come into play.

So you can return the promise and others may attach their own handlers.

示例是在AJAX请求之后刷新插件:

$.ajaxPrefilter(function(opt, origOpt, jqxhr) {
    jqxhr.always(function() {
        $("[data-plugin]").plugin();
    });
});

Jquery相关问答推荐

JQuery AJAX数据表保留前导零

使用 howler.js 中的变量播放多种声音

使用 shell 脚本判断 json 数组响应是否具有特定用户名和状态的 jq 命令

使用 JQuery 在 span 标签中用逗号分隔页面上的文本

使用 jQuery 时何时/为什么要在变量前加上$?

动态加载 css 样式表在 IE 上不起作用

bootstrap 模式中的自动完成问题

在范围内设置文本

jquery 淡入淡出元素不显示样式为可见性:隐藏的元素

如何在 jQuery Select 器中定义 css :hover 状态?

如何使用 jQuery 将表格的一行滚动到视图 (element.scrollintoView) 中?

jQuery Keypress 箭头键

删除所有子元素的 CLASS

你如何获得文本区域中的光标位置?

使用 时如何从 select2 中获取选定文本

jQuery UI 中的 disableSelection 用于什么?

jQuery:如何从 $.ajax.error 方法中获取 HTTP 状态代码?

更改 Eclipse 设置以忽略特定文件上的错误

通过单击按钮获取表格行的内容

使用 TypeScript 设置 window.location