将json与html文件分开

时间:2017-05-22 14:15:35

标签: javascript jquery html json

我开始使用html图表来显示来自json文件的数据。直到五天前,我很少用html图表做任何事情。但现在就是我所做的一切。

所以我使用的是anychart图表,我一直试图找到一种用'json`文件填充图表的方法。

经过多次试错后,我能够稍微分离数据并将其移至json文件。问题是该文件不完全是json字符串。

如您所见, MyFile.json 具有json字符串和一些图表组件。我希望我的json文件只是json数据;其他一切应该在html,另一个javascript或其他任何地方。但它不能在json文件中。

换句话说, MyFile.json 应该只包含这个:

  

{“x”:“1月”,“价值”:10000},{“x”:“2月”,“价值”:12000},{“x”:“3月”,“价值”:18000} ]

这可能吗?任何帮助表示赞赏。谢谢。

这是 MyFile.json

{
    "chart": {
        "type": "line",
        "series": [{
            "seriesType": "spline",
            "data": [{
                "x": "January",
                "value": 10000
            }, {
                "x": "February",
                "value": 12000
            }, {
                "x": "March",
                "value": 18000
            }]
        }],
        "container": "container"
    }
}

这是我的html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.anychart.com/js/7.13.1/anychart-bundle.min.js"></script>
    <link rel="stylesheet" href="https://cdn.anychart.com/css/latest/anychart-ui.min.css">
</head>
<body>
    <div id="container"></div>
</body>
</html>


<script>

    $(document).ready(function(){
        $.getJSON('MyFile.json', function(data) {
            console.log(data);
            anychart.fromJson(data).draw();
        });
    });

</script>

3 个答案:

答案 0 :(得分:2)

如果我正确地理解了你的问题......在Anycharts中可能有一种方法可以更好地完成这项工作(比如将一个对象指定为“设置”,然后使用“数据”分配另一个对象),但这里是您可以自己实现的一种方式:

JSON文件:

[{
  "x": "January",
  "value": 10000
}, {
  "x": "February",
  "value": 12000
}, {
  "x": "March",
  "value": 18000
}]

javascript文件中的AJAX请求:

$(document).ready(function(){
    $.getJSON('MyFile.json', function(data) {
        var wrapper = {
          "chart": {
            "type": "line",
            "series": [{
              "seriesType": "spline",
              "data": data // adding the ajax response data
            }],
            "container": "container"
          }
        };
        anychart.fromJson(wrapper).draw();
    });
});

答案 1 :(得分:0)

您可以使用data-*属性将json数据嵌入到html元素中。

答案 2 :(得分:0)

一种方法是先将每个图表附加到容器中,然后使用该系列设置jquery数据。

    $.getJSON('MyFile.json', function (charts) {
    for (var i = 0, len = charts.length; i < len; i++) {
        $('#container').append('<div id="chart_' + i + '"></div>');
        $('chart_' + i).data('series', charts[i].series.data);
    }
});