我一直试图通过本地数据库上的一些数据来处理一些Google Charts。我想我现在已经正确地推出了JSON。
{
"cols": [
{
"id": "",
"label": "Inits",
"pattern": "",
"type": "string"
},
{
"id": "",
"label": "SalesVal",
"pattern": "",
"type": "number"
}
],
"rows": [
{
"c": [
{
"v": "IS",
"f": null
},
{
"v": "1708.6000",
"f": null
}
]
},
{
"c": [
{
"v": "NS",
"f": null
},
{
"v": "1098.8200",
"f": null
}
]
},
{
"c": [
{
"v": "RC",
"f": null
},
{
"v": "458.8200",
"f": null
}
]
}
]
}
我正在使用它作为HTML。
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "getData.php",
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});
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
我已经过了几次,看不出我哪里出错了。
答案 0 :(得分:2)
它发生在SalesVal
列为number
类型但单元格包含字符串值的情况下。
根据Format of the Constructor's JavaScript Literal data Parameter:
type [Required]
列中数据的数据类型。支持 以下字符串值(示例包括v:property,描述 后):
- 'number' - JavaScript数值。示例值:
v:7 , v:3.14, v:-55
话虽如此,您可以考虑以下选项:
选项1。修改getData.php
端点以返回google.visualization.DataTable
的有效 json数据:
"v": "1708.6000" //invalid (current)
"v": 1708.6000 //valid
选项2
确保number type
的数据列包含JavaScript编号值,如下所示:
实施例
var jsonData = {
"cols": [
{
"id": "",
"label": "Inits",
"pattern": "",
"type": "string"
},
{
"id": "",
"label": "SalesVal",
"pattern": "",
"type": "number"
}
],
"rows": [
{
"c": [
{
"v": "IS",
"f": null
},
{
"v": "1708.6000",
"f": null
}
]
},
{
"c": [
{
"v": "NS",
"f": null
},
{
"v": "1098.8200",
"f": null
}
]
},
{
"c": [
{
"v": "RC",
"f": null
},
{
"v": "458.8200",
"f": null
}
]
}
]
};
google.load('visualization', '1', { 'packages': ['corechart'] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(prepareJsonData(jsonData));
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, { width: 400, height: 240 });
}
function prepareJsonData(json) {
json.rows.forEach(function(row) {
row.c[1].v = parseFloat(row.c[1].v); //ensure number cell value
});
return json;
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="chart_div"></div>