jQuery $ .get或$ .post来捕获页面加载错误(例如404)
当您使用$ .get或$ .post时,如何捕获未找到的服务器错误或404页面?
例如:
$.post("/myhandler", { value: 1 }, function(data) { alert(data); });
如果存在加载“/ myhandler”的服务器错误,或者如果找不到它,那将绝对没有任何作用。
如果出现错误,如何通知您?
在$.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){} });
演示
你能做到的
$.post("/myhandler", { value: 1 }, function(data) { alert(data); }).fail(function(){ // Handle error here });
如果出现错误,将调用fail
其他答案都很好,但是还有其他解决方案,即.ajaxSetup
, .ajaxError
和其他Ajax事件处理程序(有关其余部分的更多信息,请查看ajaxSetup文档页面)。
例如,使用.ajaxError
您可以为.post
, .get
, .getJSON
和.ajax
设置一个特定元素集的所有ajax错误的全局处理程序。
$(selector).ajaxError(function(event, xhr, ajaxOptions, errorThrown) { // handle ajax error here });
请改用$.ajax
并使用error
回调。
尝试使用$.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/"})