我正在尝试使用php PDO绘制DB表,我使用以下代码成功地实现了这一点:
test.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?
发布于 2015-05-28 20:06:42
在php文件中,在关闭标签之后,你需要写JS部分,就像它
<script type="text/javascript" charset="utf-8">
var data = <?php echo json_encode($results); ?>;
</script>
注意使用分号。只需要修改一小段JS脚本,但我认为您可以做到。
发布于 2015-05-28 20:21:12
// test.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);
header('Content-type: application/json');
echo $json;
//js
...
if (Morris.EventEmitter) {
//if you use jQuery
$.get('/test.php', {}, function(result) { //or use $.getJSON
dashboardMainChart = Morris.Area({
...
data: result,
...
如果不使用jQuery,则为xmlhttp
发布于 2015-05-28 20:29:59
您需要回显内容类型,以便浏览器看到返回的数据并接受为json。
echo ('Content-type: application/json');
$json = json_encode($results);
echo $json;
我通常打开google控制台或firefox的firebug来查看您发送到的网络选项卡上的response选项卡。从那里,您可以看到从服务器返回的数据,以检查您是否回显正确的数据。
此外,您还可以通过插件将它们打印到控制台日志中
console.log(data);
在您的javascript中,以确认您是否以正确的格式获取数据。
你不妨看看一些db文档,从中提取出你需要的数据。
不是SELECT * FROM pdotable,而是选择period,sales,profit。
希望这能有所帮助。
https://stackoverflow.com/questions/30515956
复制相似问题