2012-01-18 98 views
12
覆蓋錯誤

我有一個默認的jQuery AJAX的錯誤處理下面的代碼:jQuery.ajaxSetup:用的StatusCode

$.ajaxSetup({ 
    error : function(jqXHR, textStatus, errorThrown) { 
     alert("Error: " + textStatus + ": " + errorThrown); 
    }, 
    statusCode : { 
     404: function() { 
      alert("Element not found."); 
     } 
    } 
}); 

然而,當404發生時,這兩個函數upcalled:第一錯誤,然後的StatusCode ,所以我看到2個連續的警報。

如何防止這種行爲,並得到錯誤回調只有的StatusCode不是upcalled?

+0

通過刪除statucCode.404? – 2012-01-18 18:33:55

+1

不,不。我想要404條件下的特定消息,否則就是默認的消息。 – weekens 2012-01-18 18:40:55

+4

我與你@weekens。 statusCode條目缺少'else',或缺少這種情況,首先調用你的statusCode處理程序並允許它抑制通用錯誤處理程序(如果需要),使整個statusCode選項無用IMO。只有在每個可能的錯誤代碼都有statusCode條目時纔可用,這是不合理的。我希望jQuery人們重新考慮這個架構。 – enigment 2012-11-08 13:42:19

回答

23

如何只是在你的錯誤處理程序檢查狀態碼404?

$.ajaxSetup({ 
    error : function(jqXHR, textStatus, errorThrown) { 
     if (jqXHR.status == 404) { 
      alert("Element not found."); 
     } else { 
      alert("Error: " + textStatus + ": " + errorThrown); 
     } 
    } 
}); 
11

試試這個:

$.ajaxSetup({ 
error : function(jqXHR, textStatus, errorThrown) { 
    if(jqXHR.status === 404) { 
     alert("Element not found."); 
    } else { 
     alert("Error: " + textStatus + ": " + errorThrown); 
    } 
} 
}); 
+1

+1。但==在這種情況下似乎比===更好。 – weekens 2012-01-18 18:56:20

相關問題