2012-05-24 39 views
14

許多失敗的jQuery ajax請求正在污染我的控制檯並出現錯誤。綜觀其產生這些控制檯錯誤代碼(jQuery的1.7.2,行8240)jQuery:捕獲ajax異常

   // 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 
+0

您可以發佈創建AJAX請求的代碼和完整的錯誤消息。 –

+0

http://api.jquery.com/ajaxError/和http://api.jquery.com/jQuery.ajax/ – Blazemonger

+1

您是否嘗試在'$ .ajax'調用周圍添加'try/catch'塊?我不確定這個錯誤是什麼意思,但看起來像是在嘗試發出請求時發生的,我認爲'.ajaxError'只適用於響應中的錯誤。 – bfavaretto

回答

3

你可以試試這個(在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

+0

有趣的方法。 – Randomblue

5

您可以使用自定義功能來做到這一點

$(document).ajaxError(ajaxErrorHandler); 

並設置你需要做的任何處理

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

好吧,我試過了,但是然後'ajaxErrorHandler'被執行*在控制檯錯誤之上! – Randomblue

+1

謝謝!這真的幫助我:) – GobSmack

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

我得到500內部服務器錯誤當它指向我行xhr.send((s.hasContent && s.data) || null);

但是當我檢查apache日誌(對於內部服務器錯誤)錯誤w作爲其他代碼中的其他內容。

請檢查一次。