javascript - JSON 到 HTML 表 JavaScript 不工作

标签 javascript jquery html json

JSON 到 HTML 表格 JavaScript 不工作

我编写此函数是为了在 HTML 表格中显示 JSON 文件的内容。但是,它返回为 undefined

我似乎无法弄清楚为什么会这样。控制台日志显示数据很好,但不是 HTML 表格。

我想知道它是否与解析数组的方式有关?

我想保持代码简洁明了,但想知道是否有更好的方法来做到这一点而不会出现 undefined 错误。也许 Vanilla JavaScript 更好,使用 fetch

可在此处找到实时页面:LBRYnomics

提前致谢!

jQuery(document).ready(function($) {     $.getJSON('https://www.brendonbrewer.com/lbrynomics/subscriber_counts.json', function(data) {
    var humanTimeSub = `${data.human_time_utc}`
    $(".human-time-sub").html(humanTimeSub)
    var sub_data = '';
    $.each(data, function(key, value) {
      sub_data += '<tr>';
      sub_data += '<td>' + value.ranks + '</td>';
      sub_data += '<td>' + value.vanity_names + '</td>';
      sub_data += '<td>' + value.claim_ids + '</td>';
      sub_data += '<td>' + value.subscribers + '</td>';
      sub_data += '</tr>';
      console.log(key + '=' + value);
    });
    $('#sub-stats').append(sub_data);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="sub-stats">
  <tr>
    <th>RANK</th>
    <th>VANITY NAME</th>
    <th>CLAIM ID</th>
    <th>SUBS</th>
  </tr>
</table>

最佳答案

每个属性都有多个不同的数组。

假设它们都处于相同的关系顺序中,您可以遍历其中一个数组并使用迭代索引访问每个其他数组中的相应元素。

类似于:

jQuery(document).ready(function($) {     $.getJSON('https://www.brendonbrewer.com/lbrynomics/subscriber_counts.json', function(data) {
    var humanTimeSub = `${data.human_time_utc}`
    $(".human-time-sub").html(humanTimeSub);        
    
    var sub_data = '';
    $.each(data.ranks, function(i, rank) {
      sub_data += '<tr>';
      sub_data += '<td>' + rank + '</td>';
      sub_data += '<td>' + data.vanity_names[i] + '</td>';
      sub_data += '<td>' + data.claim_ids[i] + '</td>';
      sub_data += '<td>' + data.subscribers[i] + '</td>';
      sub_data += '</tr>';
      //console.log(key + '=' + value);
    });
    $('#sub-stats').append(sub_data);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="sub-stats">
  <tr>
    <th>RANK</th>
    <th>VANITY NAME</th>
    <th>CLAIM ID</th>
    <th>SUBS</th>
  </tr>
</table>

关于javascript - JSON 到 HTML 表 JavaScript 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57862617/

相关文章:

javascript - jQuery 日期选择器。 2 个日期选择器。限制范围 : Max date of 2 weeks from the selected start date

javascript - 无法使用子字符串从javascript获取所需的值

jquery - fancybox 内容出现在我的页面底部

javascript - 用js打印数组并用jQuery添加html

jquery - 将鼠标悬停在导航栏上,将透明 Logo 更改为填充 Logo

html - jQuery Mobile 水平选择 - 最小宽度

javascript - 从页面顶部滚动之前页面会闪烁到 anchor

javascript - 如果按下某个键 500 毫秒,则会触发一个函数

javascript - 加载文档时的全屏浏览器窗口

javascript - 使用 css 选择器作为 javascript 的输入