如何使AJAX同步(SJAX) [英] How do I make AJAX synchronous (SJAX)
本文介绍了如何使AJAX同步(SJAX)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这个想法是让AJAX请求在继续执行之前等待控制器的回复.这是因为我在for循环中实现了AJAX.
The idea is to make AJAX request wait for the controller reply before continuing execution. This is because I implemented AJAX inside a for loop.
for (var i = 0; i <= qtg.length-1; i++) {
index++;
gq(type, objParams.intro + " #" + index, qtg[i]); // ajax request happens here
}
function gq(type, intro, qtg) {
var new_question_params = "type=" + type+ "&intro=" + intro+ "&q=" + qtg;
$.ajax({
type: "POST",
async: false, // async set to false doesnt do a thing
url: "./cntlr/generate/",
data: new_question_params,
success: function(data, textStatus, jqXHR) {
console.log("created order : " + (data.q.order));
},
dataType: "json"
});
}
预期输出应为:
创建的订单:1
created order : 1
创建的订单:2
创建的订单:3
创建的订单:4
Ajax返回:
创建的订单:4
created order : 4
创建的订单:2
创建的订单:1
创建的订单:3
有什么想法吗?
推荐答案
答案
虽然异步可能会等待AJAX执行,但是循环中的代码仍在同时进行所有4个调用.
Answer
While async might wait for the AJAX execution, your code inside the loop is still making all 4 call at the same time.
不确定为什么要执行循环,但这是进行AJAX回调的好地方,例如:
Not sure why you're doing the loop, but this is a great place to make AJAX callbacks, like this:
var totalNumber = qtg.length;
function gq(type, intro, i) {
var new_question_params = "type=" + type+ "&intro=" + intro+ "&q=" + qtg[i];
$.ajax({
type: "POST",
async: false, // async set to false doesnt do a thing
url: "./cntlr/generate/",
data: new_question_params,
success: function(data, textStatus, jqXHR) {
console.log("created order : " + (data.q.order));
if (i < totalNumber)
gq(type, intro, i+1);
},
dataType: "json"
});
}
这篇关于如何使AJAX同步(SJAX)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文