jQuery AJAX调用中有没有类似于“finally”的东西?

在jQuery AJAX调用中是否有Java“最终”模拟? 我在这里有这个代码。 在我总是我抛出一个exception,但是我总是希望它去的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"); }); 

我试图使用done()complete()和另一个always() ,但似乎没有任何工作。

这里是JSFiddle:

http://jsfiddle.net/qv3t3L0m/

看到这个例子:

 $.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). } }); 

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

.always()应该工作。 请参阅http://api.jquery.com/jQuery.ajax/上的;“jqXHR对象”部分。

jqXHR.always(function(data | jqXHR,textStatus,jqXHR | errorThrown){}); 完整callback选项的替代构造,.always()方法replace了不推荐的.complete()方法。

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

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

以下build议在jQuery中不起作用,因为jQuery的promise实现不处理传递给方法的错误。 我只是把它们留在这里作为说明,如果jQuery是承诺/ 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"); }); 

虽然我不确定jquery的promise是否总是支持,但是另一种方法是使用then(again)并传递与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"); }); 

有一个错误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"); } } }); 

对不起,坏英语! 欢呼;-)

对于那些使用jQuery 3.0及更高版本的人来说,

弃用声明:从jQuery 3.0开始,jqXHR.success(),jqXHR.error()和jqXHR.complete()callback被删除。 您可以使用jqXHR.done(),jqXHR.fail()和jqXHR.always()来代替。

正如在官方文件中