javascript - 使用 jquery 和 json 显示数组中的所有项目

标签 javascript jquery arrays json

我正在尝试使用冰与火之歌 API 中的 json 和 jquery 获取数组中的所有项目以显示。我只能从每个数组中显示一项。

这是代码笔:https://codepen.io/frederickalcantara/pen/aWeXOz

var data;

$.getJSON(characters[i], function(json) {
    data = json;

    var alliance = $('#alliance');
    for (var i = 0; i < data.allegiances.length; i++) {
        if (i === data.allegiances.length - 1) {
            $.getJSON(data.allegiances[i], function(json1) {
               alliance.html(json1.name);
            });
        } else {
            $.getJSON(data.allegiances[i], function(json1) {
               alliance.html(json1.name + ', ');
            });
        }

    }

    const title = $('#title');

    if (data.titles.length === "") {
        return 'N/A';
    } else {
        for (i = 0; i < data.titles.length; i++) {

            if (i === data.titles.length - 1) {
                title.html(data.titles[i]);
            } else {
                title.html(data.titles[i]) + ', ';
            }

        }


    const tv = $('#seasons');

    for (var i = 0; i < data.tvSeries.length; i++) {
        if (i === data.tvSeries.length - 1) {
            tv.html(data.tvSeries[i]);
        } else {
            tv.html(data.tvSeries[i] + ', ');
        }
    }

    const actor = $('#actors')
    if (json.playedBy === "") {
        return 'N/A';
    } else {
        actor.html(json.playedBy);
    }

});

最佳答案

主要问题是你的循环。您不断替换 html 元素中的值,直到数组中的最后一个值。您可以像这样简化此代码:

  title.html(data.titles.join(','));

它取代了所有这些:

 for (i = 0; i < data.titles.length; i++) {

        if (i === data.titles.length - 1) {
            title.html(data.titles[i]);
        } else {
            title.html(data.titles[i]) + ', ';
        }

    }

更新:处理效忠问题。 此处使用 Promise 很重要,因为您正在进行大量 AJAX 调用,并且需要确保它们在尝试显示它们之前已得到解决。您可以将整个 for 循环替换为忠诚度,如下所示:

  Promise.all(data.allegiances.map(function(ally){
     return new Promise(function(resolve, reject){
         $.getJSON(ally, function(json) {
               resolve(json.name);
         });
     });
   }))
   .then(function(allies){
     alliance.html(allies.join(', '));
   });

关于javascript - 使用 jquery 和 json 显示数组中的所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44296640/

相关文章:

javascript - VueJS : Re-create component after clicking on the same "router-link"?

javascript - AngularJs 和套接字服务器

c++:本地数组定义与 malloc 调用

java - 存储具有 x 和 y 坐标的对象网格以描述它们的位置。阵列是可接受的解决方案吗?

javascript - react : Getting active element name from <ul> in to the header

javascript - 砖石 + 同位素 + imagesLoaded 未定义 yii

javascript - rails : How to loading Animations with jQuery UJS in form submit button?

jQuery Mobile 多页面模板请求错误页面

javascript - 自定义对象上的 jQuery val() 方法

arrays - 某些数据更改后如何刷新 TableView?