2011-01-14 124 views
13

当您使用$ .get或$ .post时,如何捕获Server Error或404页面未找到?

例如:

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

那将什么都不做,如果有一个服务器错误装载“/将myHandler”,或者,如果没有找到它。

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

回答

20

使用error处理器上$.ajax()

$.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

+6

因此,这是不可能的$不用彷徨? – 2013-01-17 21:52:03

+0

同上,可以做类似的负载()? – 2014-01-18 05:42:02

5

其他的答案很不错,一切,但有替代解决方案,即.ajaxSetup.ajaxError和其他Ajax事件处理程序(检查ajaxSetup文档页面的其他信息)。

例如,.ajaxError你可以设置从.post.get.getJSON.ajax所有你的Ajax错误的一组特定元素的一个全球性的处理程序。

$(selector).ajaxError(function(event, xhr, ajaxOptions, errorThrown) { 
    // handle ajax error here 
}); 
33

你可以做

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

失败将被调用,如果那里有一个错误

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