Javascript jQuery.post() 失败回调函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6046898/
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
jQuery.post() failure callback function?
提问by McRonald
Let's say I've a code:
假设我有一个代码:
$.post("test.php", function(data) {
alert("Data Loaded: " + data);
});
Is there any way to check if the request have failed (e.g. due to the timeout)?
有没有办法检查请求是否失败(例如由于超时)?
回答by amosrivera
Yes there is, from the jQuery documentation:
是的,来自jQuery 文档:
$.post("test.php", function(data) {
alert("Data Loaded: " + data);
})
.fail(function() {
alert("error");
})
Update: drake7077: "error is deprecated as of jquery 1.8, use .fail()"
更新:drake7077:“错误从 jquery 1.8 开始被弃用,使用 .fail()”
回答by Pointy
Two possibilities:
两种可能:
You can register an "ajax error" general callback, which will be called when any ajax operation fails:
$(document).ajaxError(function(event, jqXHR, settings, exception) { ... });
You can fall back to
$.ajax()
instead and include your own error handler directly.
你可以注册一个“ajax error”通用回调,当任何ajax操作失败时都会调用它:
$(document).ajaxError(function(event, jqXHR, settings, exception) { ... });
您可以
$.ajax()
改用并直接包含您自己的错误处理程序。
edit— @amosrivera is right - the new "Deferred" return values allow for introduction of handlers. Those are available with jQuery 1.5 and newer.
编辑——@amosrivera 是对的——新的“延迟”返回值允许引入处理程序。这些在 jQuery 1.5 和更新版本中可用。