这是我的array.php,其中json数据来自数据库,我从下面的脚本中得到了完美的结果
$table = [];
$table['cols'] = array(
array('id' => '', 'label' => 'Topping', 'type' => 'string'),
array('id' => '', 'label' => 'Slices', 'type' => 'number')
);
$tableName = array('1' => "tb", '2' => 'tb1');
foreach ($tableName as $key => $value) {
$row = [];
$qry = "SELECT topping, slices FROM $value";
$result = mysqli_query($con,$qry);
foreach ($result as $row) {
$temp = [];
$temp[] = array('v' => (string) $row['topping']);
$temp[] = array('v' => (int) $row['slices']);
$rows[] = array('c' => $temp);
}
$result->free();
$table['rows'] = $rows;
}
mysqli_close($con);
$jsonTable = json_encode($table, true);
echo $jsonTable;
** Array.php数据输出Ex:**
{"cols":[{"id":"","label":"Topping","type":"string"},{"id":"","label":"Slices","type":"number"}],"rows":[{"c":[{"v":"MAX"},{"v":150}]},{"c":[{"v":"MAX1"},{"v":59}]},{"c":[{"v":"MAX2"},{"v":15}]},{"c":[{"v":"MAX3"},{"v":153}]},{"c":[{"v":"MAX4"},{"v":8}]},{"c":[{"v":"MAX5"},{"v":25}]},{"c":[{"v":"MAX6"},{"v":65}]}]
}
这是我的Ajax函数,我从array.php中调用数据
var jsonData = $.ajax({
url: "array.php",
dataType:"json",
}).responseText;
var data = new google.visualization.DataTable(JSON.parse(jsonData)); var options = { 标题:'我的日常活动' }; var chart = new google.visualization.PieChart(document.getElementById(' piechart')); chart.draw(数据,选项);
**但我仍然会遇到错误请帮助**
答案 0 :(得分:2)
好的,我已将你的json输出复制到这样的php文件(jsondata.php)中:
$out = '{"cols":[{"id":"","label":"Topping","type":"string"},{"id":"","label":"Slices","type":"number"}],"rows":[{"c":[{"v":"MAX"},{"v":150}]},{"c":[{"v":"MAX1"},{"v":59}]},{"c":[{"v":"MAX2"},{"v":15}]},{"c":[{"v":"MAX3"},{"v":153}]},{"c":[{"v":"MAX4"},{"v":8}]},{"c":[{"v":"MAX5"},{"v":25}]},{"c":[{"v":"MAX6"},{"v":65}]}]}';
echo $out;
使用它,我已经修改了一点你的javascript
var jsonData = $.ajax({
url: "jsondata.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('piechart'));
var options = { title: 'My Daily Activities' };
chart.draw(data, options);
注意2件事:
Ajax调用中的async:false
。这实际上违背了Ajax的本质,但它是谷歌展示示例的方式,它也是解决问题的最简单方法。
var data = new google.visualization.DataTable(jsonData);
这对我有用,希望它能解决你的问题。