2011-08-09 49 views
1

我有一個jQuery .each循環與一個.get裏面。我想等到循環內部的所有內容都完成後(每次將一個新元素push到數組中),然後對php文件發出ajax post請求以保存創建的數組。我不知道如何讓ajax請求等到每個完成。到目前爲止,ajax很快就會發射,因此陣列內部仍然是空的,因爲它們內部的火焰在發射時還沒有完成。也許你有一個想法。讓阿賈克斯等待,直到每個完成

這裏是腳本:

$('#ScanButton, .ScanButton').click(function() { 

var array = ["http://www.xyz.com/bla/bla/summary.html", 
      "http://www.xyz.com/blu/blu/summary.html", 
      ]; 

dataArray = []; 

$.each(array, function(n, val) { 


    $.get(val, function(res) { //get the html source of this website 



     var data = { 

     } 

    }).complete(function() { 
     alert("complete"); 
     dataArray.push(data); 
    }); 

}); 

    data = YAHOO.lang.JSON.stringify(dataArray);  

    $.ajax({ 
    async:   false, 
    type:   'post', 
    cache:   false, 
    url:   'test.php', 
    data:   {myJson: data} 
    }); 

    return false; 

});

我很感激任何幫助。謝謝:)

+0

請問「同源策略」是一個問題,因爲獲得()函數是阿賈克斯(),這是受此影響的速記功能。更多信息可以在http://en.wikipedia.org/wiki/Same_origin_policy找到?希望有所幫助。 –

+0

我很熟悉同源策略的概念。謝謝!:)我有一個可行的解決方法(這只是一個私人項目)。但是直到現在,在每個循環之後,ajax post請求被觸發。我想將這些請求最小化爲一個。這就是爲什麼在完成循環並且完成數組傳遞之後應該觸發最後的ajax post請求。 – Sebsemillia

回答

1

Underscore.js有一個elegant solution to this sort of problem

var renderNotes = _.after(notes.length, render); 
_.each(notes, function(note) { 
    note.asyncSave({success: renderNotes}); 
}); 
// renderNotes is run once, after all notes have saved.