【问题标题】:Google Charts: Cannot read property '0' of undefined谷歌图表:无法读取未定义的属性“0”
【发布时间】:2016-02-05 10:33:55
【问题描述】:

我似乎无法让谷歌图表处理 JSON 数据。 我收到此错误:'Cannot read property '0' of undefined.' JSON 响应确实具有 JSON 内容类型集。我环顾了类似的问题,但似乎找不到任何解决方案。

Javascript:

google.load('visualization', '1', {
  packages: ['corechart']
});
google.setOnLoadCallback(get_data);

function get_data() {
  $.getJSON('/api?data=graphs', function(json) {
    var status = json.status;
    render_chart(status);
  });
}

function render_chart(status) {
  var status_chart = new google.visualization.DataTable(status);
  var options_status_chart = {
    lineWidth: 0,
    areaOpacity: 0.5
  }
}

JSON 响应:

{
  "status": {
     "cols": [{
        "type": "string",
        "label": "Date - Time",
        "id": "dt_metric"
     }, {
        "type": "number",
        "label": "Status",
        "id": "s_metric"
     }],
     "rows": [{
        "c": [{
           "v": "2016\/1\/5 - 09:30"
        }, {
           "v": 0
        }]
     }, {
        "c": [{
           "v": "2016\/1\/5 - 10:00"
        }, {
           "v": 1
            }]
         }]
    }
}

【问题讨论】:

  • 提供的代码和 JSON 工作正常。你确定你有正确的网址吗? console.log(json); 带给你什么?
  • 是的,我已经使用了控制台日志,它们返回“对象 {cols: Array[2], rows: Array[97]}”。这就是为什么我不明白什么不起作用:$
  • 您何时收到错误消息?绘制图表的代码在哪里?

标签: javascript json ajax google-visualization


【解决方案1】:

您的 JSON 响应有问题,文件末尾缺少大括号。这就是为什么它没有被解析为正确的 JSON。

【讨论】:

  • 抱歉,这是我写问题时的错误。我现在已经更新了这个问题。我检查了我的整个 JSON 响应,它是有效的。谢谢。
  • 您的 JSON 看起来符合 google-chart。我认为您没有访问 json 对象。您可以删除对 render_chart() 的调用并改为使用 console.log(Object.keys(json).length) 吗?
  • 我很确定这是范围问题。出于测试目的,将您的 dataTable 声明为 null 全局。在 get_data() 函数中添加:status_chart = new google.visualization.DataTable(json.status) 并移除对 render_chart 的调用。
  • 对不起,我有点困惑,如果我这样做并删除对 render_chart 的调用,那么什么都不会发生?
  • 检查您是否能够正确构建数据表。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-03
  • 2017-11-09
  • 2021-11-03
  • 1970-01-01
  • 2019-11-20
相关资源
最近更新 更多