在所有呼叫完成之前,Ajax呼叫For循环,For循环完成 [英] Ajax Call in For Loop, For Loop Completing Before all Calls are Made
问题描述
我创建了一个for循环,循环元素在容器中出现的次数。 for循环从HTML中获取一些数据并创建一个JSON url,然后返回一个值。然后应该将该值添加到适当位置的HTML中。
I have created a for loop that loops the number of times that an element appears in a container. The for loop grabs some data from the HTML and creates a JSON url which will then return a value. That value should then be added to the HTML in the appropriate place.
问题似乎是在完成所有Ajax调用之前for循环完成,所以只有最后一个值正被添加到HTML中。我认为我可以确保readystate等于4,但该解决方案不起作用。我也尝试使用完整的,而不是成功的Ajax事件。任何见解?这是我的代码。
The problem seems that the for loop completes before all of the Ajax calls are made, so only the last value is being added to the HTML. I thought that I could make sure that the readystate is equal to 4, but that solution did not work. I also tried using complete, rather than success as an Ajax Event. Any insights? Here is my the code.
for(var index = 0; index < $('#wizSteps #step6 label').length; index++){
var priceCount;
console.log(index);
var currentSelect = $('#wizSteps #step6 label[data-pricepos="'+index+'"]');
url = 'http://www.thesite.com/api/search.json?taxonomy=cat3435' + currentSelect.find('input').attr('name');
jQuery.ajax({
url: url,
dataType: "JSON",
success: function( data ){
var totalResult = data.totalNumberOfResults;
console.log(currentSelect);
currentSelect.find('.itemCount').text(totalResult);
}
});
}
推荐答案
看起来你不喜欢我必须要求按顺序完成请求,你只需要以一种有效的方式跟踪 currentSelect
。为此,您可以使用上下文
ajax选项:
It looks like you don't necessarily need the requests to finish in order, you just need to keep track of currentSelect
in a way that works. For that, you can use the context
ajax option:
for (var index = 0; index < $('#wizSteps #step6 label').length; index++) {
var currentSelect = $('#wizSteps #step6 label[data-pricepos="' + index + '"]');
url = 'http://www.thesite.com/api/search.json?taxonomy=cat3435' + currentSelect.find('input').attr('name');
jQuery.ajax({
url: url,
dataType: "JSON",
context: currentSelect,
success: function (data) {
var totalResult = data.totalNumberOfResults;
this.find('.itemCount').text(totalResult);
}
});
}
这篇关于在所有呼叫完成之前,Ajax呼叫For循环,For循环完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!