You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

谷歌图表报错Cannot read property 'DataTable' of undefined求助

解决Google Charts中"Cannot read property 'DataTable' of undefined"错误

这个报错的核心问题是Google Charts库还没加载完成,你就提前调用了它的API,另外代码里还有几个小问题需要一起修正,我来一步步帮你解决:

问题分析

  1. 加载时机错误:你写的google.charts.setOnLoadCallback(drawChart(myobj))是直接执行了drawChart(myobj),而不是把函数作为回调传给Google Charts。这会导致在Google Charts还没初始化好的时候就调用new google.visualization.DataTable(),自然会报undefined的错误。
  2. 加载语法不正确:google.charts.load的参数格式不对,正确的写法应该指定版本和需要加载的图表包。
  3. 数据添加逻辑错误:addRow()无参数会添加空行,而addRows(myobj[i].time)的写法不符合要求,需要把time和speed配对成行数据。

修正后的完整代码

function updatereport() {
  $.ajax({
    url: 'getreport.php',
    data: { yy: '18', mm: '05', dd: '17', hh: '18', driverid: '7' },
    type: 'get',
    error: function() {
      alert("some error ! :(");
    },
    success: function(result) {
      var myobj = JSON.parse(result);
      // 修正Google Charts加载语法,加载当前版本的corechart包
      google.charts.load('current', {'packages': ['corechart']});
      // 用匿名函数包裹drawChart,传递参数同时保留回调引用
      google.charts.setOnLoadCallback(function() {
        drawChart(myobj);
      });
    }
  });
}

// Draw the chart and set the chart values
function drawChart(myobj) {
  var data = new google.visualization.DataTable();
  data.addColumn("number", "time");
  data.addColumn("number", "speed");
  
  // 修正数据添加逻辑:循环遍历myobj,把每个元素的time和speed作为行添加
  for (var i = 0; i < myobj.length; i++) {
    data.addRow([myobj[i].time, myobj[i].speed]);
  }

  // Optional; add a title and set the width and height of the chart
  var options = {
    'title': 'My Average Day',
    'width': 550,
    'height': 400
  };

  // Display the chart inside the <div> element with id="chart"
  var chart = new google.visualization.LineChart(document.getElementById('chart'));
  chart.draw(data, options);
}

关键改动说明

  • 把google.charts.load的参数改成标准格式,确保正确加载corechart包;
  • 用匿名函数包裹drawChart(myobj),这样既可以传递myobj参数,又能让Google Charts在加载完成后再执行这个函数;
  • 修复了数据添加的循环逻辑,确保每一行都包含time和speed两个数据,符合DataTable的要求。

内容的提问来源于stack exchange,提问作者arvin atri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:23:00