如何修复Google Chart加载API数据显示“No Data”的问题
修复Google Charts显示“No Data”的问题
我帮你定位到了两个关键问题,调整代码后就能正常显示图表了:
问题分析
addRows参数格式错误:Google Charts的DataTable.addRows()方法需要接收二维数组(每个子数组对应一行数据),但你当前传递的是一维数组,导致数据无法被正确解析。- 未遍历所有数据项:你只处理了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
相关产品推荐
相关产品推荐

