jQuery $ .get或$ .post来捕获页面加载错误(例如404)

时间:2011-01-14 01:39:22

标签: jquery post get

当您使用$ .get或$ .post时,如何捕获未找到服务器错误或404页面?

例如:

$.post("/myhandler", { value: 1 }, function(data) {
  alert(data);
});

如果服务器错误加载“/ myhandler”,或者找不到它,那么这绝对没有。

如果出现错误,如何通知您?

5 个答案:

答案 0 :(得分:39)

你可以做到

$.post("/myhandler", { value: 1 }, function(data) {
  alert(data);
}).fail(function(){ 
  // Handle error here
});
如果出现错误

,将调用

失败

答案 1 :(得分:23)

$.ajax()

上使用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){}
});

demo

答案 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回调。

http://api.jquery.com/jQuery.ajax/

答案 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/"})