我有一个 js for 循环,在循环内它会从 php 脚本中获取值。
如何在脚本进一步执行之前收集所有值?
我现在拥有的:
for(var i=0; i<TabelArray.length; i++) {
$.get({
url: drawURL + '/tabelPrice&name=' + name + '&width='+ width + '&height=' + height,
dataType: 'json',
success: function(data) {
//console.log("succes");
console.log(data);
},
error: function() {
callback(false);
}
});
}
console.log("after loop");
打印出: “循环后” “值1” “值2”
我怀疑/需要的地方: “值1” “值2” “循环后”
最佳答案
您必须使用回调等待所有调用返回:
var results = [];
var after_loop = function () {
console.log("after loop");
// do whatever you want with results
};
var process_data_ok = function (data) {
console.log(data);
results.push(data);
if ( results.length == TabelArray.length ) {
after_loop();
}
};
var process_data_fail = function () {
console.log(false);
results.push(false);
if ( results.length == TabelArray.length ) {
after_loop();
}
};
for(var i=0; i<TabelArray.length; i++) {
$.get({
url: drawURL + '/tabelPrice&name=' + name + '&width='+ width + '&height=' + height,
dataType: 'json',
success: process_data_ok,
error: process_data_fail
});
}
关于javascript - 如何在进一步执行 js 之前从循环中收集 $.get 的所有结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48180321/