jQuery:捕获ajax异常

时间:2012-05-24 15:08:18

标签: jquery ajax

许多失败的jQuery ajax请求正在检查我的控制台是否有错误。查看产生这些控制台错误的代码(jQuery 1.7.2,第8240行)

                // Do send the request
                // This may raise an exception which is actually
                // handled in jQuery.ajax (so no try/catch here)
                xhr.send( ( s.hasContent && s.data ) || null );

我注意到该评论解释了为什么那里没有try / catch。但是,即使我的error请求中有明确的jQuery.ajax回调函数,我仍然没有jQuery.ajax处理这些错误。

如何处理jQuery ajax错误,以便错误消息出现在控制台中?

编辑:以下是执行ajax请求的代码段,以及准确的错误消息(在Chrome中):

$.ajax({
    dataType: 'xml',
    url: "./python/perfdata.xml?sid=" + (new Date()),
    success: function (data) {
        var protocols = $("Protocols", data).children();

        parseData(protocols);
    },
    error: function (error) {
        setTimeout(getData, 200);
    }
});

以下是Chrome错误消息:

GET
http://zeus/dashboard/python/perfdata.xml?sid=Thu%20May%2024%202012%2016:09:38%20GMT+0100%20(GMT%20Daylight%20Time)
jquery.js:8240

4 个答案:

答案 0 :(得分:6)

您可以使用自定义功能

 $(document).ajaxError(ajaxErrorHandler); 

并在该处理程序中设置您需要做的任何事情

var ajaxErrorHandler = function () {
        //do something
    }

答案 1 :(得分:3)

如果要进行测试,可以通过覆盖“send”函数来尝试这个(在chrome中运行良好):

$(function() {

    var xhr = null;

    if (window.XMLHttpRequest) {
        xhr = window.XMLHttpRequest;
    }
    else if(window.ActiveXObject('Microsoft.XMLHTTP')){
        // I do not know if this works
        xhr = window.ActiveXObject('Microsoft.XMLHTTP');
    }

    var send = xhr.prototype.send;
    xhr.prototype.send = function(data) {
        try{
            //TODO: comment the next line
            console.log('pre send', data);
            send.call(this, data);
            //TODO: comment the next line
            console.log('pos send');
        }
        catch(e) {
            //TODO: comment the next line
            console.log('err send', e);
        }
    };

    $.ajax({
        dataType: 'xml',
        url: "./python/perfdata.xml?sid=" + (new Date()).getTime(),
        success: function (data) {
            var protocols = $("Protocols", data).children();

            parseData(protocols);
        },
        error: function (error) {
            setTimeout(getData, 200);
        }
    });
});

test

答案 2 :(得分:2)

你尝试过吗?

  $.ajaxSetup({
    timeout:10000,
    beforeSend: function(xhr) {
      //
    },
    complete:function(xhr,status) {
      //
    },      
    error: function(xhr, status, err) {
      switch (status){
      case 'timeout': {}
      case 'parseerror': {}
      case 'abort': {}
      case 'error': {}
      default: {}
      }
    }
  });

答案 3 :(得分:0)

我收到了500个内部服务器错误,当它指向行xhr.send( ( s.hasContent && s.data ) || null );

但是当我检查apache日志(内部服务器错误)时,其他一些代码中的错误是其他错误。

请检查一下。

相关问题