jQuery的阿贾克斯()使用成功,错误和完整VS .done(),.fail()和总()错误、完整、阿贾克斯、jQuery

2023-09-11 00:46:59 作者:春风乍起

的问题

如果我们改变我们的编码如以下建议? 有()之间的 .done的差异&放大器; 成功: .fail()&放大器; 错误:。总是()&放大器; 完成:

的preamble

我组建了一个jQuery.ajax电话,这是我在过去成功地做了。事情是这样的:

  $。阿贾克斯(
    {
        网址:someUrl,
        键入:POST,
        数据:someData,
        数据类型:JSON,
        成功:功能(数据){someSuccessFunction(数据); },
        错误:函数(jqXHR,textStatus,errorThrown){someErrorFunction(); }
    });
 

虽然采取了快速看一些资料,我遇到了一个参考,说明成功,错误和完整的回调pcated在jQuery 1.8代$ P $。为prepare您code为他们的最终消除,使用jqXHR.done(),jqXHR.fail(),和jqXHR.always()来代替。

我们应该因此开始编写这样的事情,而不是:

  $。阿贾克斯(使用example.php)
    .done(功能(数据){someSuccessFunction(数据);})
    .fail(功能(jqXHR,textStatus,errorThrown){someErrorFunction();})
    。总是(函数(){警报(完成);});
 
1885成为今天黄金的关键位置 有时候承认自己的错误也是另一种成功

解决方案

那么有做没有任何优势,在特定的情况下。

的点 .done() .fail() 。总是( )方法是,您可以

附加多个处理程序 请打电话让任何地方,不只是当 $。阿贾克斯

如果你在 $。阿贾克斯通话网站只安装一个处理程序,然后这些优势并没有真正发挥作用。

所以,你可以返回的承诺,其他人可能附上自己的处理程序。

例子是Ajax请求后,清爽的插件:

  $。阿贾克斯prefilter(功能(OPT,origOpt,jqxhr){
    jqxhr.always(函数(){
        $([数据插件])的插件()。
    });
});
 

The questions:

Should we change our coding as suggested below? 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

Attach multiple handlers Do so anywhere and not just when calling $.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.

Example is refreshing plugins after ajax request:

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