【问题标题】:Google Charts fetching from Json从 Json 获取的 Google 图表
【发布时间】:2016-11-27 15:13:13
【问题描述】:

我正在尝试使用 Google Charts Api 创建图表。如图所示,我的数据存储为 json 文件。

    {
        "1":[{"a":0,"d":0}],
        "2":[{"a":0,"d":0}],
        "3":[{"a":6,"d":62.92}],
        "4":[{"a":1.57,"d":75.32}],
        "5":[{"a":1.67,"d":66.45}],
        "6":[{"a":1.25,"d":76}],
        "7":[{"a":1.36,"d":75.08}],
        "8":[{"a":1.59,"d":69.27}], 
...
    }

我正在获取 json 文件,将对象推送到 javascript 数组。它没有问题。我添加了这些行以了解正在发生的事情。但是 Google Api 不接受我的值并且只显示

dots.push([5, 50]);
dots.push([7,60]);

这是我的代码

function drawDots()
{  
    var data = new google.visualization.DataTable();
    data.addColumn('number', 'a');
    data.addColumn('number', 'd');

    dots = new Array;
    dots.push([5, 50]);
    dots.push([7,60]);

    $.getJSON("/graph/graph.json", function(json)
    {
        $.each(json, function(id, num)
        {
            $.each(num, function(i, e)
            {           
                dots.push([e.a, e.d]);
            });
        }); 

    });

    data.addRows(dots);

    var options = {
        title: '',
        hAxis: {title: 'Data 1', minValue: 0, maxValue: 100},
        vAxis: {title: 'Data 2', minValue: 0, maxValue: 100},
        legend: 'none'
    };

    var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));

    chart.draw(data, options);  
}

值的数据类型是数字,我也试过 eval() 。在控制台中,值似乎在数组中。不明白怎么回事。

这是带有屏幕截图的点和数据的控制台日志。

【问题讨论】:

  • 我已经快速将您的代码放入 jsfiddle 中,它似乎工作正常,您确定有问题吗?
  • @winseybash 是的,我很确定。我编辑了问题并添加了一个 ss.来自 json 的值存在于点数组中,但它们不会传递给数据。

标签: javascript jquery json google-visualization


【解决方案1】:

问题在于异步 getJSON 调用。发生了 getJSON 调用,但当它仍在检索 graph.json 的内容时,其余代码将执行。这意味着 getJSON 回调在图表绘制后运行。

解决方法:将图表绘制代码移到getJSON回调中:

function drawDots()
{  
    var data = new google.visualization.DataTable();
    data.addColumn('number', 'a');
    data.addColumn('number', 'd');

    dots = new Array;
    dots.push([5, 50]);
    dots.push([7,60]);

    $.getJSON("/graph/graph.json", function(json)
    {
        $.each(json, function(id, num)
        {
            $.each(num, function(i, e)
            {           
                dots.push([e.a, e.d]);
            });
        }); 

        data.addRows(dots);

        var options = {
            title: '',
            hAxis: {title: 'Data 1', minValue: 0, maxValue: 100},
            vAxis: {title: 'Data 2', minValue: 0, maxValue: 100},
            legend: 'none'
        };

        var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));

        chart.draw(data, options);
    }); 
}

【讨论】:

  • 有道理 :) 谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-09
  • 2015-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多