Http请求通过AJAX发送2次

时间:2013-11-25 11:39:15

标签: javascript php 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次。我正在接受2次Http响应。我写了console.log(“更新表”),它显示了2次。我很困惑为什么我收到2次Http响应,而不是我只发送1个请求?

3 个答案:

答案 0 :(得分:0)

您未在readyState处理程序中测试onreadystatechange。每次状态改变时,该函数都会触发。当readyState不是完成时,通常会中止该功能(通过返回)。

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

答案 1 :(得分:0)

您在请求过程中收到多个readyState事件。你想要的只是在请求完成时才收到通知。

使用以下方法扩展您的处理程序:

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

}

更新: 原始问题通过简单的等式检查(无类型)解决,这导致假设在某些浏览器中readyState是包含string typed field的{​​{1}}。

number

答案 2 :(得分:0)

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

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

只有readyState为4时,才会完成请求。

此致 UDI