我正在尝试使用 php PDO 绘制数据库表,我使用以下代码成功制作了该表:
测试.php
<?php
$dbh = new PDO("mysql:host=localhost;dbname=test", "root", "");
$statement=$dbh->prepare("SELECT * FROM pdotable");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
echo $json;
?>
我需要将结果放入图表JS代码中,他的数据数组在此代码中:
initCharts: function() {
if (Morris.EventEmitter) {
// Use Morris.Area instead of Morris.Line
dashboardMainChart = Morris.Area({
element: 'sales_statistics',
padding: 0,
behaveLikeLine: false,
gridEnabled: false,
gridLineColor: false,
axes: false,
fillOpacity: 1,
data:
[{
period: '2011',
sales: 1400,
profit: 400
}, {
period: '2011 Q2',
sales: 1100,
profit: 600
}, {
period: '2011 Q3',
sales: 1600,
profit: 500
}, {
period: '2011 Q4',
sales: 1200,
profit: 400
}, {
period: '2012 Q1',
sales: 1550,
profit: 5
}],
lineColors: ['#399a8c', '#92e9dc'],
xkey: 'period',
ykeys: ['sales', 'profit'],
labels: ['Sales', 'Profit'],
pointSize: 0,
lineWidth: 0,
hideHover: 'auto',
resize: true
});
}
},
如何将 data : [json]
替换为 PHP 结果中的 JSON?
最佳答案
在关闭标签后的php文件中,您需要编写JS部分,就像这样
<script type="text/javascript" charset="utf-8">
var data = <?php echo json_encode($results); ?>;
</script>
小心分号。只需要修正一点 JS 脚本,但我认为你可以做到。
关于javascript - JSON从php到JS文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30515956/