简体   繁体   English

jQuery ajax()使用成功,错误和完成vs .done()、. fail()和always()

[英]jQuery ajax() using success, error and complete vs .done(), .fail() and always()

The questions : 问题

  1. Should we change our coding as suggested below? 我们是否应该按照以下建议更改编码?
  2. Is there a difference between .done() & success: , .fail() & error: and .always() & complete: ? .done()success: ,. .fail()error:.always()complete:之间是否有区别?

The preamble : 序言

I was putting together a jQuery.ajax call, which I have done successfully in the past too. 我正在整理一个jQuery.ajax调用,我在过去也做得很成功。 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. 在快速浏览一些文档时,我遇到了一个参考资料,指出从jQuery 1.8开始不推荐使用成功,错误和完整的回调。 To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead. 要准备将其最终删除的代码,请改用jqXHR.done(),jqXHR.fail()和jqXHR.always()。

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 .done() .fail() .always()方法的重点是您可以

  1. Attach multiple handlers 附加多个处理程序
  2. Do so anywhere and not just when calling $.ajax 可以在任何地方进行操作,而不仅仅是在调用$.ajax

If you are at the $.ajax call site only attaching single handlers then those advantages don't really come into play. 如果您在$.ajax呼叫站点仅附加单个处理程序,则这些优势并没有真正发挥作用。

So you can return the promise and others may attach their own handlers. 因此,您可以退还诺言,其他人可以附加自己的处理程序。

Example is refreshing plugins after ajax request: 示例是在ajax请求之后刷新插件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM