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 );

我注意到这个评论解释了为什么没有尝试/抓住那里.但是,即使我的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

解决方法

你可以尝试这个(在chrome中运行良好),如果是测试,覆盖函数“send”:
$(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

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: <span id=&quot...
jQuery 添加水印 <script src="../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...