【问题标题】:jQuery - Maintain Order of .each() while using .getJSONjQuery - 使用 .getJSON 时保持 .each() 的顺序
【发布时间】:2017-08-02 15:57:54
【问题描述】:

我有一个工作函数,它检查具有特定类名的任何输入,然后为每个输入的值运行 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://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
        }
      });
    });
  }
}

它可以工作,但是因为它是异步的,所以它不会按页面上的输入顺序返回。如何修改现有函数,使数据以与输入相同的顺序显示?

【问题讨论】:

  • 每次调用.each() 都会为您提供一个索引。一种可能性是创建一个长度与您发出的请求数相同的数组,并且每次返回响应时,将响应放入数组中该迭代的索引处。
  • ...然后,您可以在完成后处理它们,或者维护一个从 0 开始的单独计数器,每次将新项目添加到数组时,尝试从当前迭代计数器的位置,直到它达到数组中的undefined 值。这样您就可以为页面提供有序的更新,而无需等待它们全部完成。

标签: javascript jquery ajax each getjson


【解决方案1】:

如果您想等到他们都回来,您可以将结果保存在一个数组中,并记住您看到了多少个结果;当您看到与请求一样多的结果时,您就完成了。见 cmets:

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
                    }
                });
        });
    }
}

【讨论】:

  • 感谢您的帮助!欣赏信息丰富的 cmets。通过在 .always() 函数中包含一个 for 循环来输出每个提要的 HTML 元素,能够完美地集成并输出输入的顺序。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-08
  • 2014-09-29
  • 1970-01-01
  • 2012-03-16
  • 1970-01-01
  • 2010-09-17
  • 1970-01-01
相关资源
最近更新 更多