jQuery:捕获ajaxexception

许多失败的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 。 但是,即使我的jQuery.ajax请求中有一个显式的error回调函数,我仍然没有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 

如果要进行测试,可以通过覆盖函数“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); } }); }); 

测试

您可以使用自定义function来执行此操作

  $(document).ajaxError(ajaxErrorHandler); 

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

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

你试过了吗?

  $.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: {} } } }); 

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

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

请检查一下。