2016-09-27 64 views
0

我有一個PHP頁面,其形式爲,其中有100個字段。我使用Ajax在的數據中輸入內容到每個字段。阿賈克斯形式超時

有時,它發生,我得到這個錯誤:

net::ERR_CONNECTION_TIMED_OUT

大概是因爲服務器不能及時響應。發生這種情況時,出現錯誤,Ajax將無法繼續工作。

有沒有一種方法可以讓代碼在出錯後執行?這樣我可以繼續嘗試Ajax嗎?

注意:我使用的是老式的XMLHttpRequest()要求,而不是jQuery函數

+0

請發表您的代碼 - 這樣有」在這裏實際上是錯誤的猜測 – eithed

回答

1

在您的Ajax代碼嘗試定義超時設置爲0(無限制):

$.ajax({ 
timeout: 0, //Set your timeout value in milliseconds or 0 for unlimited 

您可以將此值設置爲3秒(3000)並使用錯誤函數捕獲異常。就像這樣:

error: function(jqXHR, textError, errorThrown) { 
    if(textError==="timeout") { 
     alert("Call has timed out"); //Handle the timeout 
    } else { 
     alert("Unknown error"); //Handle other error type 
    } 

希望這將有助於

+0

我沒有使用jquery,我使用普通的舊XMLHttpRequest(),我會嘗試使用超時與該https://developer.mozilla.org/en-US/docs/ Web/API/XMLHttpRequest/timeout –

+0

據我所知,添加超時只會決定多長時間g腳本應等待響應,如果響應失敗,腳本是否會停止工作?或者它會採取下一個Ajax請求,並繼續他們?如果發生錯誤,Chrome似乎會取消所有的腳本執行,有沒有辦法在Chrome中繞過它? –

+0

您可以通過以下鏈接訪問chrome事件:chrome:// net-internals /#events 查看爲什麼被取消 –

-1

您可以使用此功能來捕獲所有樣的錯誤,你可以在阿賈克斯獲得:

$.ajax({ 
    url: "your_url", 
    type: "GET", 
    dataType: "json", 
    timeout: 5000, /* timeout in milliseconds */ 
    success: function(response) { alert(response); }, 
    error: function(jqXHR, exception) { 
     if (jqXHR.status === 0) { 
      return ('Not connected.\nPlease verify your network connection.'); 
     } else if (jqXHR.status == 404) { 
      return ('The requested page not found. [404]'); 
     } else if (jqXHR.status == 500) { 
      return ('Internal Server Error [500].'); 
     } else if (exception === 'parsererror') { 
      return ('Requested JSON parse failed.'); 
     } else if (exception === 'timeout') { 
      return ('Time out error.'); 
     } else if (exception === 'abort') { 
      return ('Ajax request aborted.'); 
     } else { 
      return ('Uncaught Error.\n' + jqXHR.responseText); 
     } 
    } 
});​