2013-11-25 39 views
0

發送2次我的AJAX代碼如下:HTTP請求是通過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個請求的事實?

+1

是否有可能顯示,此代碼運行的背景下? – melc

+0

melc它發送請求upload.php上傳數據upload.php腳本運行良好。我檢查過它 –

回答

0

您在請求過程中收到多個readyState事件。你想在這裏只是在請求完成時才被通知。

擴展您的處理程序與此:

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

} 

UPDATE: 原來的問題是用簡單的平等檢查(無類型),這導致了假設,即在某些瀏覽器readyState的是包含number一個string typed field解決。

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

} 
+1

ok先生,那麼我應該複製粘貼我的功能在這個檢查? –

+0

是的,就是這樣:) –

+0

sir xhr.readyState === 4不工作,它沒有顯示任何東西 –

0

您未在您的onreadystatechange處理程序中測試readyState。每次狀態改變時,該功能都會觸發。當readyState不是完成時,通常中止函數(通過返回)。

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

先生爲什麼你寫了this.readyState!== 4? –

+0

@MuneemHabib - 出於代碼前段描述的原因。 – Quentin

+0

先生this.readystate!== 4,我提醒一些文本,它幾乎被稱爲4次 –

0

我認爲問題在於你沒有檢查xhr的readyState值。 的onreadystatechange的回調代碼應與if語句包裹:

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

只有當readyState爲4,請求實際上完成。

問候, 烏迪

+0

sir xhr.readyState === 4不工作它不顯示無關 –