【发布时间】:2013-06-27 07:52:31
【问题描述】:
所以这是我的设置:我在多个元素上调用 .each,经过几次检查后,我发送了一个带有一些 JSON 数据的 ajax 请求,成功后我将服务器响应作为属性应用到每个元素(它通常是一个ID)。之后,我将 id 推送到一个数组。
问题是显然 ajax 请求是异步的,并且使用元素 id 数组的函数在所有 ajax 有时间完成之前触发。
我尝试过使用 .when 和 .then 但回调函数总是在 ajax 之前被触发。
这是我的代码的外观(我删除了一些不必要的部分):
var order = [];
function sub(selector){
selector.each(function(){
var out = {
"some":"random",
"stuff":"here"
};
$.ajax({
type: "POST"
url: "/test/url",
dataType: 'json',
contentType: "application/json; charset=utf-8",
data:JSON.stringify(out),
success:function(response){
$(this).attr("data-response",response);
order.push(response);
}
})
})
}
$("#button").click(function(){
$.when(sub($(".test"))).then(function() {
console.log(order);
//i have to run the sub function twice so the order doesn't return undefined
});
});
【问题讨论】:
-
您可以继续检查 order 数组中的 itmes 数量,直到它与 selector.each 的大小相同。使用 setInterval
标签: javascript jquery ajax callback