【问题标题】:jQuery $.get or $.post to catch page load error (eg. 404)jQuery $.get 或 $.post 捕获页面加载错误(例如 404)
【发布时间】:2011-01-14 01:39:21
【问题描述】:

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

例如:

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

如果加载“/myhandler”时出现服务器错误,或者找不到它,那绝对不会做任何事情。

如果有错误,你如何让它通知你?

【问题讨论】:

    标签: jquery post get


    【解决方案1】:

    你可以的

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

    如果有错误会调用fail

    【讨论】:

    • +1 表示失败功能。它完成了工作!你可以这样使用它: .fail(function(e){ if(e.status == 404){ // ... } else{ // ... } });
    • 带有 .error() 的旧代码没有捕获任何东西。只需将其切换为 fail() 即可。
    • 这应该是公认的答案,因为它直接回答了问题,而不是要求每个人使用不同的功能。
    【解决方案2】:

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

    【讨论】:

    • 那么 $.get 不可能吗?
    • @Reigel 美丽!没有意识到加载回调有一个状态参数。
    【解决方案3】:

    其他答案都很好,但还有其他解决方案,即.ajaxSetup.ajaxError 和其他 Ajax 事件处理程序(请查看 ajaxSetup 文档页面了解更多信息)。

    例如,使用.ajaxError,您可以为一组特定元素设置来自.post.get.getJSON.ajax 的所有ajax 错误的全局处理程序。

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

    【讨论】:

      【解决方案4】:

      改用$.ajax 并使用error 回调。

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

      【讨论】:

        【解决方案5】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-12-11
          • 1970-01-01
          • 2013-10-03
          • 2012-02-23
          • 2012-08-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多