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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:43:38  来源:igfitidea点击:

jQuery $.get or $.post to catch page load error (eg. 404)

jquerypostget

提问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

use errorhandler on $.ajax()

使用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

演示

回答by mekwall

The other answers are nice and all, but there's alternative solutions, namely .ajaxSetup, .ajaxErrorand other Ajax event handlers (check the ajaxSetup doc page for more info on the rest).

其他答案都很好,但还有其他解决方案,即.ajaxSetup,.ajaxError和其他 Ajax 事件处理程序(查看 ajaxSetup 文档页面以获取有关其余部分的更多信息)。

For example, with .ajaxErroryou can setup a global handler of all your ajax errors from .post, .get, .getJSONand .ajaxfor a specific set of elements.

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

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

回答by coreyward

Use $.ajaxinstead and use the errorcallback.

使用$.ajax替代和使用error回调。

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

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

回答by guest271314

Try using $.ajaxSetup(), stausCodeoption

尝试使用$.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/"})