【问题标题】:Create table form JSON从 JSON 创建表
【发布时间】:2020-10-18 12:32:09
【问题描述】:

我正在尝试从 JSON 创建一个表。而且我认为我的链接有问题,但也不是。我的表上没有数据。我的错误是:

无法读取未定义的属性“符号” '未捕获的类型错误:无法读取未定义的属性'符号' 在对象。 (main.js:14) 在 Function.each (jquery.min.js:2) 在 Object.success (main.js:11) 在你(jquery.min.js:2) 在 Object.fireWith [as resolveWith] (jquery.min.js:2) 在 k (jquery.min.js:2) 在 XMLHttpRequest。'

这是我的 JS 代码

$(document).ready(function() {
  $.getJSON("https://api.coindesk.com/v1/bpi/currentprice.json", function(json) {

    enter code here

    var currentprice = '';
    $.each(json.bpi, function(key, value) {
      var USD = value.USD
      currentprice += '<tr>';
      currentprice += '<td>' + USD.symbol + '</td>';
      currentprice += '<td>' + USD.description + '</td>';
      currentprice += '<td>' + USD.rate + '</td>';
     
      currentprice += '</tr>';
    });
    $("#current_table").append(currentprice);
  })
})

谢谢

【问题讨论】:

    标签: javascript html jquery json


    【解决方案1】:

    检查值是否存在,如果值不存在则设置为空字符串。

    var currentprice = '';
    $.each(json.bpi, function(key, value) {
    var USD = value.USD
    var symbol = USD.symbol || ""
    var description = USD.description || ""
    var rate = USD.rate || ""
    += '<tr>';
    += '<td>' + symbol + '</td>';
    += '<td>' + description + '</td>';
    += '<td>' + rate + '</td>';
    
    += '</tr>';
    });
    $("#current_table").append(currentprice);
    

    【讨论】:

      【解决方案2】:

      您正在循环通过json.bpi,这将给您USD,GBP..etc,所以只需使用value.keyname 从json 对象中获取特定值。

      演示代码:

      $(document).ready(function() {
        $.getJSON("https://api.coindesk.com/v1/bpi/currentprice.json", function(json) {
          var currentprice = '';
          $.each(json.bpi, function(key, value) {
            currentprice += '<tr>';
            currentprice += '<td>' + value.symbol + '</td>';
            currentprice += '<td>' + value.description + '</td>';
            currentprice += '<td>' + value.rate + '</td>';
      
            currentprice += '</tr>';
          });
          $("#current_table").append(currentprice);
        })
      })
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <table id="current_table" border='1'>
      </table>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-28
        • 2015-08-31
        • 2014-08-02
        相关资源
        最近更新 更多