我有一个ajax
调用来检索数据,并且成功后,运行循环并运行运行更多ajax
次调用的函数。
CODE:
success: function(data){
// FIRST MAKE SURE DATA WAS FOUND
console.log(data);
if(data["status"] == "found")
{
// CREATE NEEDED ARRAY FROM SINGLE STRING
var restrictionArray = data["data_retrieved"].split(',');
loop_amount = restrictionArray.length; //<!-- AMOUNT TO BE LOOPED FOR BUILDING FORMS
//var Action = this.Elevation.getActionsByOptionId(Option.getID())[i];
for(var j = 0; j < loop_amount; j++)
{
var EditRowRestriction = OptionRules.prototype.getEditRowRestriction(j);
var check = $(EditRowRestriction).find("select");
console.log(check[0]);
var EditRowRestirction_select_ability = OptionRules.prototype.getEditRowRestriction_select_ability(j);
//var EditRowRestirction_access_ability = OptionRules.prototype.getEditRowRestriction_access_ability(j);
EditRowRestriction.onremove = function()
{
$(this).next().empty(); <!-- RESTRICTION SELECT ABILITY REMOVE
//$(this).next().next().empty(); <!-- RESTRICTION ACCESS ABILITY REMOVE
$(this).empty();
//var Action = this.Action;
//that.removeAction(Action);
}
tbody.appendChild(EditRowRestriction);
tbody.appendChild(EditRowRestirction_select_ability);
console.log(check[1]);
}
}
},
error:function(){
alert("An error occured, please try again.");
}
继承问题,在for loop
内;这些方法链接到另一个调用ajax
调用的方法。这里发生的事情甚至是在ajax
调用结束之前,循环始终在继续,并且这些方法总是被调用。我想要做的是停止循环,直到这些方法根据ajax
调用完成返回。而不是在循环中调用最后两行代码:
tbody.appendChild(EditRowRestriction);
tbody.appendChild(EditRowRestirction_select_ability);
实现这一目标的最佳方法是什么?
建议,想法?
答案 0 :(得分:1)
最好使用单个服务器端脚本合并所有这些循环,但是,如果这不是一个选项,则可以使用.then:
var def = $.Deferred(function(def){
def.resolve();
}).promise(); // used to start .then chain
for (var i = 0; i < 10; i++) {
def = def.then(function () {
return $.ajax({});
});
}
def.done(function(){
// All requests from chain are done
console.log('all done');
});
答案 1 :(得分:-1)
您可以修改循环内对$ .ajax的调用,以便同步执行,而不是异步执行。 (参见问题How can I get jQuery to perform a synchronous, rather than asynchronous, AJAX request?。)这会产生&#34;暂停&#34;内部ajax调用执行时的循环。这将是最简单的方法,但确实具有在执行这些ajax请求时锁定用户浏览器的缺点。
另一种方法是将循环分解成代码,以便在内部ajax调用完成后调用的回调函数中完成循环处理。