对于每个命令文件,我需要等待ajax成功,然后继续执行下一个命令.
问题是for a循环在ajax代码完成之前移动到下一个命令.有人能提供解决方案吗?
对于每个循环:
$.each(cmd_files, function(index, cmd) {
update_log('Running CMD for' + cmd)
wait_for_cmd_complete(cmd).done(function(data){
update_log("CMD is complete");
})
})
Ajax功能:
function wait_for_cmd_complete(cmd){
return $.ajax({
type: 'POST',
data: {cmd:cmd},
url: 'wait_for_cmd_complete.PHP'
});
}
解决方法:
这根本不是你如何编写事件驱动的动作.如果您需要下一代代码迭代才能在事件之后启动,那么您不会遍历迭代…因为那将在事件之前运行所有代码!这就是事件的运作方式.
制作类似这种通用结构的东西可以更好地在每个事件中运行1次迭代代码:
var i = 0; // the index we're using
var list = []; // array of the things you plan on "looping" through
var max = list.length; // basically how many iterations to do
function nextIteration() {
if (i >= max) return; // end it if it's done
// do whatever you want done before the event for this iteration
list[i].addEventListener("someevent", onEvent); // add whatever event listener
}
function onEvent() {
// do whatever it is you want done after the event for this iteration
i++; // up the index
nextIteration(); // start the next iteration
}
nextIteration(); // start the first iteration manually
为了便于说明,您可以知道发生了什么,这里的代码格式就像上面的代码一样.
var i = 0; // the index we're using
update_log('Running Cmds');
var cmd; // basically a var just so we don't have to keep calling cmd_files[i]
var totalCommands = cmd_files.length; // basically how many iterations to do
function sendNextCommand() {
if (i >= totalCommands) return; // end it if it's done
cmd = cmd_files[i]; // again, just so we don't have to keep calling cmd_files[i]
update_log("Waiting for CMD " + cmd + " to complete...");
$.ajax({type:'POST', data:{cmd:cmd}, url:'wait_for_cmd_complete.PHP'}).done(onCommandComplete);
// above line does what needs to be done (sends to PHP) and then adds the event listener 'done'
}
function onCommandComplete(value) {
update_log( " CMD complete for: " + cmd);
i++; // up the index
sendNextCommand(); // start the next iteration
}
sendNextCommand(); // start the first iteration manually
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。