2015-01-31 78 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