许多失败的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 );
Run Code Online (Sandbox Code Playgroud)
我注意到这个评论解释了为什么没有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);
}
});
Run Code Online (Sandbox Code Playgroud)
这是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
Run Code Online (Sandbox Code Playgroud)
您可以使用自定义功能来执行此操作
$(document).ajaxError(ajaxErrorHandler);
Run Code Online (Sandbox Code Playgroud)
并设置你在该处理程序中需要做的任何事情
var ajaxErrorHandler = function () {
//do something
}
Run Code Online (Sandbox Code Playgroud)
如果要进行测试,您可以尝试此操作(在 chrome 中效果很好),方法是覆盖函数“send”:
\n\n$(function() {\n\n var xhr = null;\n\n if (window.XMLHttpRequest) {\n xhr = window.XMLHttpRequest;\n }\n else if(window.ActiveXObject(\'Microsoft.XMLHTTP\')){\n // I do not know if this works\n xhr = window.ActiveXObject(\'Microsoft.XMLHTTP\');\n }\n\n var send = xhr.prototype.send;\n xhr.prototype.send = function(data) {\n try{\n //TODO: comment the next line\n console.log(\'pre send\', data);\n send.call(this, data);\n //TODO: comment the next line\n console.log(\'pos send\');\n }\n catch(e) {\n //TODO: comment the next line\n console.log(\'err send\', e);\n }\n };\n\n $.ajax({\n dataType: \'xml\',\n url: "./python/perfdata.xml?sid=" + (new Date()).getTime(),\n success: function (data) {\n var protocols = $("Protocols", data).children();\n\n parseData(protocols);\n },\n error: function (error) {\n setTimeout(getData, 200);\n }\n });\n});\nRun Code Online (Sandbox Code Playgroud)\n\n\xe2\x80\x8b\n测试
\n