【问题标题】:Trouble looping through an array and spitting out API results无法循环遍历数组并吐出 API 结果
【发布时间】:2021-07-13 06:12:24
【问题描述】:

我正在使用 NY state legislature API 并且遇到了麻烦,我为每个项目获得相同的输出(仅与数组中的第一项相关)。我检查了一下,柜台似乎确实在增加,所以我不确定为什么它没有显示所有的账单号码。

<script>
    $(document).ready(function() {
        const bills = ["A6143", "S737", "A2260", "S8455A", "A559", "S737", "A3041", "S1234"];
        var printNo = [];
        var title = [];
        var counter = 0;
        bills.forEach(function (item, index) {
            $.getJSON("https://legislation.nysenate.gov/api/3/bills/2021/" + bills[counter] + "?key=[mykeygoeshere]", function(item) {
                printNo[counter] = item.result.printNo;
                title[counter] = item.result.title;
                document.write("<p>" + printNo[counter] + ". ");
                document.write(title[counter] + "</p>");
                counter++;
            });
        });
    });
</script>

我最终要尝试的是比较所有账单的最新项目并显示最新更新的提要。 (例如,最近的两个动作可能是同一张账单。)但首先,我什至不知道如何在数组中迭代和显示标题,更不用说复杂的“动作”内容了。

这是 API 信息,但我认为这与这里无关。以防万一:https://legislation.nysenate.gov/static/docs/html/index.html

【问题讨论】:

    标签: javascript jquery arrays json variables


    【解决方案1】:

    您正在 jquery getJson 调用的回调中更新您的计数器。所以 forEach 的每次迭代都有相同的 counter 值。

    增加 forEach 函数主体中的计数器,与 getJSON 处于同一级别。

    您为什么还要为网址上的 bills[counter] 烦恼?您可以在 forEach 回调函数的参数中获取每个项目。

    $.getJSON("https://legislation.nysenate.gov/api/3/bills/2021/" + item...
    

    【讨论】:

      【解决方案2】:

      页面加载后您不能使用document.write。它完全消除了整个页面。由于 $.getJSON 是异步的,每组 document.write 也可能会清除之前的那些

      而是创建元素并插入到文档中,在您已经建立的容器中保存它们。

      接下来,您可以将所有这些请求映射到一个 promise 数组,并在所有请求解决后使用 Promise.all() 处理所有结果

      类似的东西:

      $(document).ready(function() {
        const apiUrl = "https://legislation.nysenate.gov/api/3/bills/2021/";
        const bills = ["A6143", "S737", "A2260", "S8455A", "A559", "S737", "A3041", "S1234"];
        // array of request promises
        const requests = bills.map(bill => {
          return $.getJSON(apiUrl + bill + "?key=[mykeygoeshere]")
        });
      
        Promise.all(requests).then(results => {
          for (let {printNo, title} of results) {
            const $p = $('<p>').text(printNo + '.' + title);                  
            $('#someContainerId').append($p)
          }   
        }).catch(err => console.log('Oooops, one of the requests failed'));
      });
      

      【讨论】:

      • 谢谢,这真的很有帮助。我试图弄清楚如何使用您的示例使 printNo 和 title 不被定义,因为我不能再只做 item.result.printNo。我看到它说“让 {printNo, title} of results”的部分,但真的不明白那行的意思?它在一个 for 循环中。也许我应该在第 6 行之后的返回承诺数组中定义这些变量?
      • 再次感谢。我添加了“console.log(results);”并且能够看到它实际上已经抓住了我认为不是的元素。它未定义的原因一定是无关的。因此,虽然我还没有弄清楚如何到达我想去的地方,但由于我可以在控制台中看到数据,这已经解决了!
      猜你喜欢
      • 1970-01-01
      • 2013-07-05
      • 1970-01-01
      • 1970-01-01
      • 2018-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多