Http请求通过AJAX发送了2次


Http request is sending 2 times through AJAX

我的AJAX代码如下:

data = new FormData();
   //  data="";
    paths = "";

    // Create a new HTTP requests, Form data item (data we will send to the server) and an empty string for the file paths.
    xhr = new XMLHttpRequest();

    // Set how to handle the response text from the server
    xhr.onreadystatechange = function(ev){
        //console.debug(xhr.responseText);
     //  console.log("success"+xhr.responseText);
    try{
      console.log($.parseJSON(xhr.responseText));
       var data=$.parseJSON(xhr.responseText);
      if(data.success=="yes"){
          projectCounter++;            
          var projectName=$.parseJSON(data.arguments);
          console.log(projectName.projectName);
          console.log('update table');
          if(projectCounter==2){
              UploadComplete(projectName.projectName);
          }

      }
     } 
     catch(e){}
    };
    // Loop through the file list
    for (var i in files){
        // Append the current file path to the paths variable (delimited by tripple hash signs - ###)
        paths += files[i].webkitRelativePath+"###";
        // Append current file to our FormData with the index of i
        data.append(i, files[i]);
    };
    // Append the paths variable to our FormData to be sent to the server
    // Currently, As far as I know, HTTP requests do not natively carry the path data
    // So we must add it to the request manually.
    data.append('paths', paths);
    // console.log(paths);   
    // Open and send HHTP requests to upload.php
    xhr.open('POST', "upload.php", true);
     console.log(data);   
    xhr.send(this.data);

我面临的问题是它发送了两次http请求。我收到了2次Http响应。我已经写了console.log("更新表"),它显示了2次。我很困惑,为什么我收到了2次Http响应,而不是我只发送了1个请求?

您在请求过程中收到多个readyState事件。您希望在这里只在请求完成时收到通知。

用这个扩展你的处理程序:

if(xhr.readyState === 4  //ready) {
}

更新:最初的问题是通过简单的相等性检查(非类型化)解决的,这导致了在一些浏览器中readyState是包含numberstring typed field的假设。

if(xhr.readyState == 4  //ready) {
}

您没有在onreadystatechange处理程序中测试readyState。每当状态发生变化时,该函数就会启动。当readyState未完成时,通常会中止函数(通过返回)。

xhr.onreadystatechange = function(ev){
    if (this.readyState !== 4) {
        return;
    }
    // ...

我认为问题在于您没有检查xhr的readyState值。onreadystatechange回调代码应该用if语句包装:

if (xhr.readyState === 4) {
    // your code here...
}

只有当readyState为4时,请求才真正完成。

谨致问候,Udi