让 ajax 等待每个 get 完成
我有一个 jquery .each 循环,里面有一个 .get 。我想等到循环内的所有获取都完成(每个获取都会在 .complete 处将一个新元素推送到数组中),然后向 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;
});
我很感激任何帮助。谢谢 :)
I have a jquery .each loop with a .get inside. I want to wait until all gets inside the loop are completed (each get pushes at .complete a new element into an array) and then make an ajax post request to a php file to save the created array. I don't know how I can make the ajax request wait until the each is finished. Until now the ajax fires very quickly and therefore the array is still empty as the gets inside the each are still not finished when it fires. Maybe you have an idea.
Here is the script:
$('#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;
});
I appreciate any help. Thank you :)
Underscore.js 有一个针对此类问题的优雅解决方案。
Underscore.js has an elegant solution to this sort of problem.