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

如何修复Google Chart加载API数据显示“No Data”的问题

修复Google Charts显示“No Data”的问题

我帮你定位到了两个关键问题,调整代码后就能正常显示图表了:

问题分析

  1. addRows参数格式错误:Google Charts的DataTable.addRows()方法需要接收二维数组(每个子数组对应一行数据),但你当前传递的是一维数组,导致数据无法被正确解析。
  2. 未遍历所有数据项:你只处理了API返回的第一个数据对象(reports.data[0]),忽略了第二个property_damage的数据,相当于只给图表提供了半条有效数据。

修复后的完整代码

<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
  // Create the data table.
  $.ajax({
    url: "https://api-url",
    type: 'GET',
    success: function (reports) {
      var data = new google.visualization.DataTable();
      data.addColumn('string', 'Kind Of');
      data.addColumn('number', 'Total');
      
      // 遍历所有报告数据,构建符合要求的行数组
      var chartRows = [];
      reports.data.forEach(function(reportItem) {
        chartRows.push([reportItem.report_type, reportItem.Counts]);
      });
      
      // 将行数据添加到DataTable
      data.addRows(chartRows);
      
      var options = { 'width':400, 'height':300 };
      var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }
  });
}
</script>
<div class="box-body">
  <div class="chart">
    <div id="chart_div" style="border: 1px solid #ccc"></div>
  </div>
</div>

关键修改说明

  • 新增了chartRows数组,通过forEach遍历API返回的所有data项,把每个报告类型和对应的计数组成子数组存入其中,确保最终是二维数组格式。
  • 用data.addRows(chartRows)一次性将所有行数据添加到表格,这样图表就能获取到完整的robbery和property_damage两组数据了。

如果还是有问题,可以在success回调里加一句console.log(reports),确认API返回的数据结构和你预期的完全一致,排除数据接收异常的情况。

内容的提问来源于stack exchange,提问作者Ikram Shabri

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:41:36