Javascript jQuery-在使用.getJSON时保持.each()的顺序
我有一个工作函数,用于检查具有特定类名的任何输入,然后为每个输入的值运行getJSON调用:Javascript jQuery-在使用.getJSON时保持.each()的顺序,javascript,jquery,ajax,each,getjson,Javascript,Jquery,Ajax,Each,Getjson,我有一个工作函数,用于检查具有特定类名的任何输入,然后为每个输入的值运行getJSON调用: function getTopFeeds() { if (jQuery('input.class-name').length > 0) { jQuery.each(jQuery('input.class-name'),function(){ var feedName = jQuery(this).val(); jQuery.getJSON("https://ap
function getTopFeeds() {
if (jQuery('input.class-name').length > 0) {
jQuery.each(jQuery('input.class-name'),function(){
var feedName = jQuery(this).val();
jQuery.getJSON("https://api.url/"+feedName).success(function(data) {
if (!(data)) {
return;
}
var result = data.results[0];
if (result) {
// Here I create HTML list items to display API data
}
});
});
}
}
它可以工作,但因为它是异步的,所以不会按页面上输入的顺序返回。如何修改现有函数,使数据以与输入相同的顺序显示?如果要等到它们全部返回,可以将结果保存在一个数组中,并记住看到的结果数量;当您看到与请求一样多的结果时,您就完成了。见评论:
function getTopFeeds() {
if (jQuery('input.class-name').length > 0) {
// Get the inputs
var inputs = jQuery('input.class-name');
// Storage for the results
var results = [];
// Counter for # of responses we've seen
var counter = 0;
// Get them
inputs.each(function(index) {
var feedName = this.value;
jQuery.getJSON("https://api.url/" + feedName)
.done(function(data) {
// Got a response, save it or null if falsy (would that really happen?)
results[index] = data ? data.results[0] : null;
})
.fail(function() {
// Error response, use null as a flag
results[index] = null;
})
.always(function() {
// Called after `done` and `fail` -- see if we're done
if (++counter === inputs.length) {
// Yes, we're done -- use the results in `results`
// Note that there will be `null`s for any that
// didn't have data
}
});
});
}
}
每次调用
.Each()
都会为您提供一个索引。一种可能是创建一个长度与请求数相同的数组,每次响应返回时,将响应放入该迭代索引处的数组中……然后,您可以在完成时处理所有响应,或者维护一个从0
开始的单独计数器,每次向数组中添加一个新项时,尝试从计数器的当前位置迭代,直到它在数组中遇到一个未定义的值。这将允许您提供页面的有序更新,而无需等待所有更新完成。感谢您的帮助!感谢提供信息的评论。通过在.always()函数中包含一个for循环来输出每个提要的HTML元素,我们能够完美地集成并输出输入顺序。