[英]Table has no columns when drawing google charts with JSON and Laravel from MySQL database
I have this situation where i execute a query and get the following table from the database: 我有这种情况,我执行一个查询并从数据库中获取以下表:
GRAD_ACAD, subtotal
'DOC', 79
'LIC', 1
'MTR', 6
By following the example showed in the docs, i call my controller in the URL: ... 按照文档中显示的示例,我在URL中调用我的控制器:...
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "{{URL::route('query01')}}",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
... ...
When i open the view, i get the Table has no columns error. 当我打开视图时,我得到表没有列错误。 However, by using firebug i do see the json which looks like the following:
但是,通过使用firebug,我确实看到了如下所示的json:
[{"GRAD_ACAD":"DOC","subtotal":79},{"GRAD_ACAD":"LIC","subtotal":1},{"GRAD_ACAD":"MTR","subtotal":6}]
I understand that i neeed to specify separately the column names and the rows. 我理解我需要单独指定列名和行。 How do i do it?
我该怎么做? Or how do I fix this?
或者我该如何解决这个问题?
Simplest way is to format rightly your json to an array, then you can use google.visualization.arrayToDataTable
最简单的方法是将json正确格式化为数组,然后可以使用
google.visualization.arrayToDataTable
function right_format(data){
var arr = [];
for (var i = 0; i < data.length; i++) {
var element = [];
if (arr.length === 0){
var columns = Object.keys(data[i]);
arr.push(columns);
};
for (var j = 0; j < columns.length; j++){
element.push(parseFloat(data[i][columns[j]]));
};
arr.push(element);
};
return arr;
}; };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.