2014-02-28 77 views
0

我嘗試使用下面的代碼來處理Ajax錯誤,但它不工作處理AJAX錯誤(純JS)

function ajaxPost(url, data, success, error) { 
    var xmlhttp = new XMLHttpRequest(); 
    xmlhttp.onreadystatechange = function() { 
     if (xmlhttp.readyState == 4 && xmlhttp.status === 200) { 
      if (typeof success === "function") { 
       success(xmlhttp.responseText); 
      } 
     }else if([404, 500 , 503, 504 ].indexOf(xmlhttp.status) > -1){ 
      if(typeof error === "function"){ 
       error();  
      } 
     } 
    } 
    xmlhttp.open("POST", url, true); 
    xmlhttp.setRequestHeader('Content-Type', 'application/json; charset=UTF-8'); 
    xmlhttp.send(JSON.stringify(data)); 
} 

我失去了在[404, 500 , 503, 504 ]任何其他狀態代碼?我不是在重新發明輪子,我已經使用原生JavaScript編寫了整個DOM,並且不想僅包含用於AJAX的80KB文件。請幫助我。

上述函數將數據成功發佈到服務器,但在服務器不可用時無法引發錯誤。請幫我解決這個問題。

+0

'的console.log(xmlhttp.status);'? – OneOfOne

回答

2
  // try this code 

      xmlhttp.onreadystatechange = function() { 
        if (xmlhttp.readyState === 4) { 

         var resp=eval('('+xmlhttp.responseText+')'); 


         if(xmlhttp.status == 200) { 

          // success 

         } else if(xmlhttp.status >= 500) { 

          // internal server error 

         } else if (xmlhttp.status >= 402 && xmlhttp.status <= 420) { 

          // error 

         } else if(xmlhttp.status == 400 || xmlhttp.status == 401) { 

          // bad request & unauthorized error 

         } 

        } 
       }; 
1

您可以隨時檢查任何沒有成功,例如:

function ajaxPost(url, data, success, error) { 
    var xmlhttp = new XMLHttpRequest(); 
    xmlhttp.onreadystatechange = function() { 
     if (xmlhttp.readyState == 4 && xmlhttp.status === 200) { 
      if (typeof success === "function") { 
       success(xmlhttp.responseText); 
      } 
     }else if(typeof error === "function" && (xmlhttp.status > 299 || xmlhttp.status < 200)){ 
      error();  
     } 
    } 
    xmlhttp.open("POST", url, true); 
    xmlhttp.setRequestHeader('Content-Type', 'application/json; charset=UTF-8'); 
    xmlhttp.send(JSON.stringify(data)); 
}