jQuery $.get 或 $.post 捕获页面加载错误(例如 404)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4687235/
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 $.get or $.post to catch page load error (eg. 404)
提问by Aximili
How do you catch Server Error or 404 page not found, when you use $.get or $.post ?
当您使用 $.get 或 $.post 时,您如何捕获服务器错误或未找到 404 页面?
For example:
例如:
$.post("/myhandler", { value: 1 }, function(data) {
alert(data);
});
That will do absolutely nothing if there is a Server Error loading "/myhandler", or if it is not found.
如果加载“/myhandler”时出现服务器错误,或者找不到它,那绝对不会做任何事情。
How do you make it notify you if there is an error?
如果有错误,你如何让它通知你?
回答by Roberto Arosemena
you could do
你可以
$.post("/myhandler", { value: 1 }, function(data) {
alert(data);
}).fail(function(){
// Handle error here
});
fail will be called if theres an error
如果出现错误,将调用失败
回答by Reigel
回答by mekwall
The other answers are nice and all, but there's alternative solutions, namely .ajaxSetup
, .ajaxError
and other Ajax event handlers (check the ajaxSetup doc page for more info on the rest).
其他答案都很好,但还有其他解决方案,即.ajaxSetup
,.ajaxError
和其他 Ajax 事件处理程序(查看 ajaxSetup 文档页面以获取有关其余部分的更多信息)。
For example, with .ajaxError
you can setup a global handler of all your ajax errors from .post
, .get
, .getJSON
and .ajax
for a specific set of elements.
例如,.ajaxError
你可以设置你所有的AJAX错误的全球处理器从.post
,.get
,.getJSON
和.ajax
一组特定的元素。
$(selector).ajaxError(function(event, xhr, ajaxOptions, errorThrown) {
// handle ajax error here
});
回答by coreyward
回答by guest271314
Try using $.ajaxSetup()
, stausCode
option
尝试使用$.ajaxSetup()
,stausCode
选项
$.ajaxSetup({
statusCode : {
// called on `$.get()` , `$.post()`, `$.ajax()`
// when response status code is `404`
404 : function (jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
}
});
// $.get("/path/to/url/");
// $.post("/path/to/url/");
// $.ajax({url:"/path/to/url/"})