当您使用$ .get或$ .post时,如何捕获未找到服务器错误或404页面?
例如:
$.post("/myhandler", { value: 1 }, function(data) {
alert(data);
});
如果服务器错误加载“/ myhandler”,或者找不到它,那么这绝对没有。
如果出现错误,如何通知您?
答案 0 :(得分:39)
你可以做到
$.post("/myhandler", { value: 1 }, function(data) {
alert(data);
}).fail(function(){
// Handle error here
});
如果出现错误,将调用失败
答案 1 :(得分:23)
error
处理程序
$.ajax({
url: "/myhandler",
data: {value: 1},
type: 'post',
error: function(XMLHttpRequest, textStatus, errorThrown){
alert('status:' + XMLHttpRequest.status + ', status text: ' + XMLHttpRequest.statusText);
},
success: function(data){}
});
答案 2 :(得分:5)
其他答案都很好,但还有其他解决方案,即.ajaxSetup
,.ajaxError
和其他Ajax事件处理程序(请查看ajaxSetup文档页面以获取有关其余部分的更多信息)。
例如,对于.ajaxError
,您可以针对特定.post
,.get
,.getJSON
和.ajax
设置所有ajax错误的全局处理程序元素集。
$(selector).ajaxError(function(event, xhr, ajaxOptions, errorThrown) {
// handle ajax error here
});
答案 3 :(得分:2)
改为使用$.ajax
并使用error
回调。
答案 4 :(得分:1)
尝试使用$.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/"})