Javascript 在ajax完成之前防止循环的回调
我读过无数类似帖子寻求帮助的例子,也读过关于回调背后理论的解释,但我就是不能理解。我已经到了这样一个阶段,我宁愿为我的特定场景找到一个解决方案,然后继续前进,即使我真的不理解“为什么/如何”工作。 我有一个ajax调用需要循环,需要找到一种方法在前一个调用完成之前阻止下一个调用。你能建议我如何使用回调或其他方法来实现这一点吗 下面是代码(它可以工作,但不能逐个运行ajax调用,因此我会遇到内存错误和页面崩溃)。运行的函数非常密集,可能需要20秒(但只有1秒)Javascript 在ajax完成之前防止循环的回调,javascript,ajax,asynccallback,Javascript,Ajax,Asynccallback,我读过无数类似帖子寻求帮助的例子,也读过关于回调背后理论的解释,但我就是不能理解。我已经到了这样一个阶段,我宁愿为我的特定场景找到一个解决方案,然后继续前进,即使我真的不理解“为什么/如何”工作。 我有一个ajax调用需要循环,需要找到一种方法在前一个调用完成之前阻止下一个调用。你能建议我如何使用回调或其他方法来实现这一点吗 下面是代码(它可以工作,但不能逐个运行ajax调用,因此我会遇到内存错误和页面崩溃)。运行的函数非常密集,可能需要20秒(但只有1秒) 函数returnAjax(Start
函数returnAjax(StartRoc、startRow)
{
var url='index.php?option=com_productfinderrtw&format=raw&task=goThroughProcess';
变量数据='STARTOC='+STARTOC+'&starttour='+startRow;
var请求=新请求({
url:url,
方法:'get',
数据:数据,
onSuccess:函数(responseText){
document.getElementById('fields-container')。innerHTML=responseText;
//我意识到这就是成功代码需要去的地方——回调属于这里吗?
}
}).send();
}
函数迭代器(StartRoc、startRow){
if(startRow允许传递ajax调用完成时将调用的回调
参数
function returnAjax(startLoc, startRow, callback) {
//...
onSuccess: function(responseText) {
document.getElementById('fields-container').innerHTML= responseText;
if (callback) {
callback.apply(this, arguments); //call the callback
}
}
//...
}
然后你可以这样做:
function runRAA(startLoc, startRow) {
startLoc = startLoc || 0;
startRow = startRow || 1;
if (startLoc < 47) {
returnAjax(startLoc, startRow, function (responseText) {
var counter = iterator(startLoc, startRow);
//do something with the response
//perform the next ajax request
runRAA(counter[0], counter[1]);
}));
}
}
runRAA(); //start the process
函数runRAA(startoc,startRow){
STARTOC=STARTOC | | 0;
startRow=startRow | | 1;
如果(摄氏度<47度){
returnAjax(startoc、startRow、function(responseText){
变量计数器=迭代器(startLoc、startRow);
//对回应做点什么
//执行下一个ajax请求
runRAA(计数器[0],计数器[1]);
}));
}
}
runRAA();//启动进程
新的请求类在哪里定义?
function runRAA(startLoc, startRow) {
startLoc = startLoc || 0;
startRow = startRow || 1;
if (startLoc < 47) {
returnAjax(startLoc, startRow, function (responseText) {
var counter = iterator(startLoc, startRow);
//do something with the response
//perform the next ajax request
runRAA(counter[0], counter[1]);
}));
}
}
runRAA(); //start the process