在我看来,错误处理程序不可用,因为它会增加混乱。
当前功能说明:
$.get(url, [data], [function(data, status, xhr){ ... }], [dataType])
添加错误处理程序时,参数将转换为:
$.get(url, [data], [function(data, status, xhr){ ... }], [function(data, status, xhr){ ... }], [dataType])
在附加错误处理程序参数的情况下,在进行 ajax 调用时很难理解您的意思是什么处理程序:
$.get('http://example.com', {query: 1}, function(result) {
//Handle the request
});
在这种情况下,处理程序是针对错误还是成功?这很难理解。当然,您可以在参数中添加一些额外的nulls,但这不是一个干净的解决方案并且会增加混乱。
$.ajax 有一个错误处理程序,因为它接受作为 JavaScript 对象的选项。如果您将错误处理程序函数指定为选项对象的属性,它不会产生任何问题。
解决办法:
只需使用承诺方法:
var xhr = $.post(...);
xhr.done(function(data, status, xhr){
//Handle when success
}).fail(function(xhr, errorType, error){
//Handle when an error occurred.
}).always(function(){
//A handler executed always, on success or error
//Use this to hide the loading image for example
})
调用时,ajax 调用函数将返回一个 promise 对象。附加到您的成功(使用done() 方法)和错误(using fail() 方法)处理程序的承诺。
在任何情况下都会执行always()(在执行done() 或fail() 处理程序之后)。完成与请求相关的任何工作很有用,例如隐藏加载图像。