【问题标题】:Load External JSON into HTML将外部 JSON 加载到 HTML
【发布时间】:2018-06-29 15:05:13
【问题描述】:

我对 HTML 非常陌生,如果这是一个愚蠢的问题,我很抱歉。

我目前有数据是一个外部的JSON,并在HTML 内调用加载。而不是加载它,我只想将它复制到 HTML 中并将其保存为其中的一部分。在不改变数据结构的情况下如何做到这一点?

示例数据 JSON:

[
{ 
    "User" : "COMP",
    "Runtime" : 931.216111111
},
{ 
    "User" : "AUTO",
    "Runtime" : 600.404444444
}
]

我在哪里加载它:

// load data
d3.json("data.json", function(error, data) {

    data.forEach(function(d) {
        d.User = d.User;
        d.Runtime = +d.Runtime;
    });

  // scale the range of the data
  x.domain(data.map(function(d) { return d.User; }));
  y.domain([0, d3.max(data, function(d) { return d.Runtime; })]);

我已经查看了答案,但我的问题是如何将其复制到 HTML 中并且仍然能够以相同的方式调用 d.Runtime 和 d.User 参数

【问题讨论】:

    标签: html json load


    【解决方案1】:

    在您的 HTML 页面中,您需要添加一个脚本标签来保存 JavaScript。将它放在正文中可能是个好主意,以便在页面加载时执行。

    <script type="text/javascript">
    
    </script>
    

    接下来,您需要为脚本标签内的数据定义一个常量。等号后面可以复制粘贴.json文件的内容:

    const data = [
      { 
        "User" : "COMP",
        "Runtime" : 931.216111111 
      },
      { 
        "User" : "AUTO",
        "Runtime" : 600.404444444
      }
    ]
    

    现在您可以在 d3.json 回调中附加代码:

    data.forEach(function(d) {
        d.User = d.User;
        d.Runtime = +d.Runtime;
    });
    
    // scale the range of the data
    x.domain(data.map(function(d) { return d.User; }));
    y.domain([0, d3.max(data, function(d) { return d.Runtime; })]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-23
      • 2018-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-26
      相关资源
      最近更新 更多