首页 > 解决方案 > 结合 api 响应到谷歌图表

问题描述

我有如下响应 api

{
  "status": 200,
  "message": "OK",
  "data": [
  {
     "_id": {
      "report_type": "robbery"
      },
     "report_type": "robbery",
     "Counts": 11
  },
  {
     "_id": {
        "report_type": "property_damage"
     },
     "report_type": "property_damage",
     "Counts": 39
   }
  ]
 }

我想插入report_typeCounts值到谷歌图表,但结果是No Data. 我试过在浏览器上使用控制台,没有警告和错误

这是谷歌图表脚本

  <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');


            data.addRows([reports.data[0].report_type, reports.data[0].Counts]);


        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>

我怎样才能解决这个问题 ?

谢谢

标签: javascriptjqueryjsongoogle-visualization

解决方案


您可以在以下链接中找到工作代码 https://codepen.io/arung86/pen/aejXdY?editors=1001

var reportData = reports.data.map((item)=>{ return [item.report_type,item.Counts]});
reportData.unshift(['Report Type','Counts']);    
var data = google.visualization.arrayToDataTable(reportData);

推荐阅读