2013-04-18 88 views
0

如果有這個jQuery腳本將文件從ftp服務器1移動到ftp服務器2.它確實有效,但我想要一個一個移動文件,而不是一次全部移動。無嚴寒與瀏覽器的「異步=假」 ..jquery等待Ajax調用完成

<script> 
    var files = new Array(); 
    files[1]="testfile1.txt"; 
    files[2]="testfile2.txt"; 
    files[3]="testfile3.txt"; 


    $('#button').click(function() { 
     $.each(files, function(key, value) { 
     jQuery.ajax({ 
     url: '/move.php', 
     method: 'GET', 
     data: { 
     file: value 
     }, 
     success: function(data) { 
      $('#'+ key).html(data); 
     } 
     }) 
    }); 
    }); 
    </script> 

回答

1

創建一個函數,將得到files數組中的下一個項目,執行AJAX調用,然後調用自身的success回調AJAX調用的。

var files = new Array(), key = 1; 
// arrays are generally indexed starting at 0, but I left the below as is 
files[1]="testfile1.txt"; 
files[2]="testfile2.txt"; 
files[3]="testfile3.txt"; 


function moveFile() { 
    if(key < files.length) { // there's a next element 
     var value = files[key]; 
     $.ajax({ 
      url: '/move.php', 
      method: 'GET', 
      data: { 
       file: value 
      }, 
      success: function(data) { 
       $('#' + key++).html(data); 
       moveFile(); 
      } 
     }); 
    } 
} 

$('#button').click(moveFile); 

我認爲使用files.pop();獲得下一個元素,但因爲我不知道你是否想在陣列保持不動這個已經用完之後,我決定來跟蹤,而不是訪問它們的索引。

1

你可以做到這一點遞歸:

var files = new Array(); 
    files[1]="testfile1.txt"; 
    files[2]="testfile2.txt"; 
    files[3]="testfile3.txt"; 

$('#button').click(function() { moveFile(files); }); 


function moveFile(fileArray) { 
    var currentFile = fileArray.shift(); 
    $.ajax({ 
    url: '/move.php', 
    method: 'GET', 
    data: { 
     file: currentFile 
    } 
    }).done(function() { 
    if(fileArray.length > 0) 
     moveFile(fileArray); 
    }); 
}