我正在尝试在Google图表中显示获取的数据,但是javascript中的PHP变量没有回显..如果我在javascript之外回显变量一切正常,所以我怀疑我的javascript中的某些内容一定是错误的..我仔细检查了一切,但我无法确定我们的问题在哪里..
代码没有显示任何错误!
这是浏览器源中的输出..
['Active Posts',$post_counts],['Categories',$category_counts],['Users',$user_counts],['Comments',$comment_counts],
有什么建议吗?
谢谢
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Data', 'Count'],
<?php
$data_text = ['Active Posts', 'Categories', 'Users', 'Comments'];
$data_count = ['$post_counts', '$category_counts', '$user_counts', '$comment_counts'];
for($i = 0; $i < 4; $i++) {
echo "['$data_text[$i]'" . "," . "$data_count[$i]],";
}
?>
]);
var options = {
chart: {
title: '',
subtitle: '',
}
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
</script>
答案 0 :(得分:3)
由于您已经使用PHP为JS输出数据,因此您只需使用json_encode将ARRAY转换为JSON数据。
<?php
$data = [
'Data' => 'Count',
'Active Posts' => $post_counts,
'Categories' => $category_counts,
'Users' => $user_counts,
'Comments' => $comment_counts
];
$json = json_encode($data);
?>
var data = google.visualization.arrayToDataTable("<?php echo $json; ?>");
答案 1 :(得分:1)
从php变量中删除引号,
使用此,
$data_count = [$post_counts, $category_counts, $user_counts, $comment_counts];
代替,
$data_count = ['$post_counts', '$category_counts', '$user_counts', '$comment_counts'];