jQuery AJAX 调用中是否有类似于“终于”的东西?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15925522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:02:19  来源:igfitidea点击:

Is there any analog to a 'finally' in jQuery AJAX calls?

javascriptjqueryajaxpromise

提问by Oliver Watkins

Is there a Java 'finally' analogue in jQuery AJAX calls? I have this code here. In my alwaysI throw an exception, however I ALWAYS want it to go to the then()method.

jQuery AJAX 调用中是否有 Java 'finally' 类似物?我这里有这个代码。我总是抛出一个异常,但是我总是希望它转到then()方法。

    call.xmlHttpReq = $.ajax({
        url : url,
        dataType : 'json',
        type : 'GET'
    }).always(function(processedDataOrXHRWrapper, textStatus, xhrWrapperOrErrorThrown) {

       throw "something";

    }).then(function() {

        alert("i want to always run no matter what");
    });

I have tried to use done(), complete(), and the another always(), but nothing seems to work.

我尝试使用done()complete()和另一个always(),但似乎没有任何效果。

Here is JSFiddle :

这是 JSFiddle :

http://jsfiddle.net/qv3t3L0m/

http://jsfiddle.net/qv3t3L0m/

回答by Rafael Gomes Francisco

See this example:

看这个例子:

$.ajax({
        type: "GET",
        dataType: dataType,
        contentType: contentType,
        async: TRUE,
        url: $('html form:nth-child(1)').attr('action') + "?" $('html form:nth-child(1)').serialize(),
        success: function(data) {
            console.log("FUNFOU!");
        },
        error: function(data) {
            console.log("N?O FUNFOU!");
        },
        complete: function(data) {
            console.log("SEMPRE FUNFA!"); 
            //A function to be called when the request finishes 
            // (after success and error callbacks are executed). 
        }
    });

For more informations: http://api.jquery.com/jquery.ajax/

更多信息:http: //api.jquery.com/jquery.ajax/

回答by jrummell

.always()should work. See the The jqXHR Objectsection at http://api.jquery.com/jQuery.ajax/.

.always()应该管用。请参阅http://api.jquery.com/jQuery.ajax/ 上的 jqXHR 对象部分。

jqXHR.always(function(data|jqXHR, textStatus, jqXHR|errorThrown) { }); An alternative construct to the complete callback option, the .always() method replaces the deprecated .complete() method.

In response to a successful request, the function's arguments are the same as those of .done(): data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail(): the jqXHR object, textStatus, and errorThrown. Refer to deferred.always() for implementation details.

jqXHR.always(function(data|jqXHR, textStatus, jqXHR|errorThrown) { }); 完整回调选项的替代构造, .always() 方法替换了已弃用的 .complete() 方法。

为了响应成功的请求,该函数的参数与 .done() 的参数相同:data、textStatus 和 jqXHR 对象。对于失败的请求,参数与 .fail() 的参数相同:jqXHR 对象、textStatus 和 errorThrown。有关实现细节,请参阅 deferred.always()。

See also http://api.jquery.com/deferred.always/

另见http://api.jquery.com/deferred.always/

回答by David McMullin

The below suggestions will not work in jQuery, because jQuery's promise implementation does not handle errors thrown in methods passed to then. I am only leaving them here as an illustration of what could be possible if jQuery was promises/A+ compliant. As Bergi rightly points out, you will have to manually wrap your code in your own try catch block.

下面的建议在 jQuery 中不起作用,因为 jQuery 的 promise 实现不处理传递给 then 的方法中抛出的错误。我把它们留在这里只是为了说明如果 jQuery 是 promises/A+ 兼容的话,可能会发生什么。正如 Bergi 正确指出的那样,您必须手动将代码包装在您自己的 try catch 块中。

call.xmlHttpReq = $.ajax({
    url : url,
    dataType : 'json',
    type : 'GET'
}).then(function(processedDataOrXHRWrapper, textStatus, xhrWrapperOrErrorThrown) {

   throw "something";

}).always(function() {

    alert("i want to always run no matter what");
});

Although I'm not sure if jquery's promise supports always, an alternative would be to use then (again) and pass the same function as both successHandler and errorHandler, like this :

虽然我不确定 jquery 的承诺是否总是支持,但另一种方法是使用 then(再次)并传递与 successHandler 和 errorHandler 相同的函数,如下所示:

call.xmlHttpReq = $.ajax({
    url : url,
    dataType : 'json',
    type : 'GET'
}).then(function(processedDataOrXHRWrapper, textStatus, xhrWrapperOrErrorThrown) {

   throw "something";

}).then(function() {

    alert("i want to always run no matter what");
},
function() {

    alert("i want to always run no matter what");
});

回答by Jayavardhan Gange

Just a note for those who use jQuery 3.0 and later

给那些使用 jQuery 3.0 及更高版本的人的注意事项

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

弃用通知:jqXHR.success()、jqXHR.error() 和 jqXHR.complete() 回调从 jQuery 3.0 开始被移除。您可以改用 jqXHR.done()、jqXHR.fail() 和 jqXHR.always()。

As in official documentation

如官方文档

回答by KingRider

There is a bug ajax is dependent on the server, need to check status with "complete" is the best, a kind of "success", "error" and others are not 100% of the PUT, POST and GET ... look at an example

有一个bug ajax是依赖服务器的,需要检查状态用“完成”最好,一种“成功”、“错误”等不是100%的PUT、POST和GET……看看举个例子

$.ajax({
    url: '/api/v2/tickets/123456.json',
    ....
    ....
    ....
    complete: function(data) { 
        if (data.statusText == "success") { 
            console.log("Sent successfully");
        } else { 
            console.log("Not Sent");
        }
    }
});

Sorry bad english! Cheer ;-)

对不起英语不好!加油;-)

回答by sairfan

if you want one code definition for all ajax requests, you can do it like this

如果你想要所有 ajax 请求的一个代码定义,你可以这样做

$(document).ajaxComplete(function () {
    console.log('ajax complete on doc');
})