2015-01-31 56 views
0

你好stackoverflow commmunity,我有奇怪的問題。 我使用ajax將文件上傳到服務器。下面是代碼:Ajax readystatechange奇怪的行爲

\t // request 
 
\t request.addEventListener('readystatechange', function(event){ 
 
\t \t if(this.readyState==4 && this.status==200){ 
 
\t \t \t if (request.responseText=="upload_successful"){ 
 
\t \t \t \t alert("Thank you for sharing past test."); 
 
\t \t \t \t $(".form").hide(); 
 
\t \t \t \t $(".overlay").hide(); 
 
\t \t \t } 
 
\t \t } 
 
\t \t else { 
 
\t \t \t alert("Sorry, there was a problems adding your test."); 
 
\t \t \t console.log("This server replied with HTTP status "+this.status); 
 
\t \t } 
 
\t });

一切正常,在我的本地,但在真正的服務器我警報消息(「對不起,出現問題等。」)顯示(兩個或三次)之後(「感謝您分享......」)警報出現,並且我的文件被上傳到服務器並添加到數據庫中。 那麼爲什麼它要兩到三次ELSE然後跳轉到IF部分。

回答

2

AJAX請求在完成之前會經過許多中間狀態。每個這些狀態更改都會觸發onreadystatechange處理程序。這些其他狀態不是錯誤,它們只是在請求完成之前的臨時條件。

錯誤由status屬性指示。如果你想報告一個錯誤,它應該是這樣的:

if (this.readyState == 4) { // request is completed 
    if (this.status == 200 && this.responseText=="upload_successful") { // request was successful 
     alert("Thank you for sharing past test."); 
     $(".form").hide(); 
     $(".overlay").hide(); 
    } else { 
     alert("Sorry, there was a problems adding your test."); 
     console.log("This server replied with HTTP status "+this.status); 
    } 
} 
-1

我通過將alert()移動到第一個IF語句找到了我的問題的解決方案,因此如果文件上傳,用戶不會再看到它。但我仍然有興趣知道爲什麼我們要跳幾次ELSE。

+1

XHR在進入狀態4之前會經歷許多中間狀態。 – Barmar 2015-01-31 18:52:35