本文介绍了我应该将.done()和.fail()用于新的jQuery AJAX代码,而不是成功和错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这样编码:

$.ajax({ cache: false,
    url: "/Admin/Contents/GetData",
    data: { accountID: AccountID },
    success: function (data) {
        $('#CityID').html(data);
    },
    error: function (ajaxContext) {
        alert(ajaxContext.responseText)
    }
});

但是,当我在最后查看jQuery .ajax()文档时,似乎建议我应该在下面进行这样的编码,或者至少建议添加.done().fail():

But when I look at the jQuery .ajax() documentation at the end it seems to suggest I should be coding like this below or at least it suggests adding a .done() and a .fail():

var request = $.ajax({ cache: false,
    url: "/Admin/Contents/GetData",
    data: { accountID: AccountID }
});

request.done(function (data) {
    xxx;
});
request.fail(function (jqXHR, textStatus) {
    xxx;
});

更新

如果我这样编写代码,将其分为三个,还是有一些优势?

If I code like this is it the same or is there some advantage to breaking it into three ?

$.ajax({ cache: false,
    url: "/Admin/Contents/GetData",
    data: { accountID: AccountID }
}).done(function (data) {
    xxx;
}).fail(function (jqXHR, textStatus) {
    xxx;
});

推荐答案

如user2246674所述,使用successerror作为ajax函数的参数是有效的.

As stated by user2246674, using success and error as parameter of the ajax function is valid.

要与先前的答案保持一致,请阅读doc:

To be consistent with precedent answer, reading the doc :

jqXHR.success(),jqXHR.error()和jqXHR.complete()回调将在jQuery 1.8中弃用.要准备将其最终删除的代码,请改用jqXHR.done(),jqXHR.fail()和jqXHR.always().

The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks will be deprecated in jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

如果使用回调操作功能(例如,使用方法链接),请使用.done().fail().always()代替success()error()complete().

If you are using the callback-manipulation function (using method-chaining for example), use .done(), .fail() and .always() instead of success(), error() and complete().

这篇关于我应该将.done()和.fail()用于新的jQuery AJAX代码,而不是成功和错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 17:21