javascript - 结合 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_type
和Counts
值到谷歌图表,但结果是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>
我怎样才能解决这个问题 ?
谢谢
解决方案
您可以在以下链接中找到工作代码 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);
推荐阅读
- eclipse - 在 Pydev 中激活虚拟环境
- php - Google ReCaptcha V2 无法使用旧的 PHP 代码
- python-3.x - Python3 Gtk3 将 GdkPixbuf 附加到 Gtk.ListStore
- python - 在python中获取每个neibours字节的一半
- jquery - 将更改其他 CSS 与类链接
- python - 如何在 Python 中覆盖 ibm_db.exec_immediate(connect, sql) 上的模式使用
- single-page-application - Blazor 页面中的不同 css 文件
- reactjs - 当我包含参数时,为什么我的提取不会完成
- c# - HttpWebRequest.GetResponse 返回 404 但 URL 在浏览器中有效
- javascript - 如何使用 HTML、JS 和 CSS 实现 android:inputType="textPassword"