2016-12-05 57 views
0

有問到這個問題,但解決方案似乎並沒有對我的工作類似的問題。我有一個Java應用程序,HTTP獲取服務器以檢索某些信息,但我正在測試此服務器未響應的情況。我正在嘗試訪問一個返回HTTP 403(禁止)響應的Web服務器,並且我想處理該錯誤。Ajax的錯誤處理程序

先用下面的代碼,我能夠做的HTTP GET,到達網頁,僅此而已。我沒有收到HTTP 403錯誤響應。 但是,如果我在以下代碼中取消超時,ajax將能夠達到錯誤並以'超時'錯誤進行響應。是的,這是一個超時錯誤,但由於HTTP 403錯誤,我想拿到403

init: function (credentials) { 
       $.ajax({ 
        type: "GET", 
        url: this.serverURL, 
        //timeout: 5000, 
        headers: { 
          Accept: "application/json" 
        }, 
        contentType: "application/json; charset=utf-8", 
        crossDomain: true, 
        cache: false, 
        data: { 
          'username': credentials.username, 
          'key': credentials.key 
        }, 
        jsonp: false, 
        dataType: 'jsonp', 
        //never enters here... 
        statusCode: { 
         404: function() { 
          alert('404 page not found'); 
         }, 

         400: function() { 
          alert('400 bad request'); 
         }, 
         403: function() { 
          alert('403 forbbiden'); 
         }}, 

        error: function (XMLHttpRequest, errorThrown) { 
         handleError(XMLHttpRequest, errorThrown); 
        } 
       }); 
     function handleError(XMLHttpRequest, errorThrown) { 

      //If not found, internal server error or forbidden (it should enter here) 
     if (XMLHttpRequest.status == 404 || XMLHttpRequest.status == 500 || XMLHttpRequest.status == 403) { 
      Logger.loginfo('never enters here...'); 
     } 
     else if (XMLHttpRequest.readyState == 4) { 
      //http error 
      Logger.loginfo('Error: ' + errorThrown); 
     } 
     else if (XMLHttpRequest.readyState == 0) { 
      // Network error, not possible to open() (i.e. connection refused, access denied...) 
      Logger.loginfo('Error: ' + errorThrown); 
     } 
     else { 
      //http error 
      Logger.loginfo('Error else!: ' + errorThrown); 
      // something after initializing/opening the HTTP GET but before completing it 
     } 
    };} 

任何幫助將是非常讚賞。

回答

0

您應該添加以下的異常,並檢查您是否正確回來讓所有的值。你

error: function(xhr, textStatus, error){ 
    console.log(xhr.statusText); 
    console.log(textStatus); 
    console.log(error); 
    //then call your function and pass the values 
    //and do the checks 
} 

也可以檢查這個答案對於其他details

+1

嗨Pritam,我得到超時錯誤在3個數量級....如果我不使用超時我從來沒有讀過任何日誌。我會繼續尋找,謝謝你的鏈接。 – agonza1