2012-05-30 39 views
9

據我瞭解,一個可能性,處理與Ajax錯誤結果是下列之一:jQuery的默認AJAX的StatusCode

$.ajax({ 
    url: someUrl, 
    type: 'POST', 
    success: function(data) {}, 
    error: function(jqXHR, exception) { 
     if (jqXHR.status === 0) { 
      alert('Not connect.\n Verify Network.'); 
     } else if (jqXHR.status == 404) { 
      alert('Requested page not found. [404]'); 
     } else if (jqXHR.status == 500) { 
      alert('Internal Server Error [500].'); 
     } else if (exception === 'parsererror') { 
      alert('Requested JSON parse failed.'); 
     } else if (exception === 'timeout') { 
      alert('Time out error.'); 
     } else if (exception === 'abort') { 
      alert('Ajax request aborted.'); 
     } else { 
      alert('Uncaught Error.\n' + jqXHR.responseText); 
     } 
    } 
}); 

,或者爲了使用statusCode,使之更具可讀性:

$.ajax({ 
    url: someUrl, 
    type: 'POST', 
    statusCode: { 
     200: function(data) { 
        : 
        : 
      }, 
     401: function() { 
        : 
        : 
      }, 
       : 
       : 

我的問題是:
是否有可能使用statusCode並有一個默認的轉場?

回答

13

不是在的StatusCode參數。但是,那是因爲如果你想抓住一切,一個更好(更精簡)的方式:

complete: function(jqXHR, textStatus) { 
    switch (jqXHR.status) { 
     case 200: 
      alert("200 received! yay!"); 
      break; 
     case 404: 
      alert("404 received! boo!"); 
      break; 
     default: 
      alert("I don't know what I just got but it ain't good!"); 
    } 
} 
+7

太好了,謝謝!真的乾淨簡單。只爲那些將要使用它的人添加,爲了從請求中獲得json,你需要使用'data = jQuery.parseJSON(jqXHR.responseText);' – guyaloni