javascript - 从 Json 获取 Google 图表

标签 javascript jquery json google-visualization

我正在尝试使用 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() 。在控制台中,值似乎在数组中。无法理解出了什么问题。

这是点和数据的控制台日志以及屏幕截图。 enter image description here

最佳答案

问题出在异步 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);
    }); 
}

关于javascript - 从 Json 获取 Google 图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40830436/

相关文章:

javascript - Google Maps v3 API 扩展边界。 Javascript 操作方法?

javascript - 命名加载文档就绪的函数

javascript - Typescript strictNullChecks 跨函数检查

javascript - jquery slider 自动播放

javascript - 防止 ASP.NET 中的按钮刷新页面

javascript - 在 HTML 中显示格式化的 JSON(大对象)

javascript - 读取 json 文件并将特定数组附加到外部范围列表 - javascript - Nodejs

javascript - D3 圆对象没有属性

javascript - JS 中的嵌套函数

javascript - 继承属性(property)检查