[英]JSON from php into JS file
我正在尝试使用php PDO绘制数据库表,我使用以下代码成功制作了该表:
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
});
}
},
我如何用PHP结果中的JSON替换data : [json]
?
在关闭标签后的php文件中,您需要编写JS部分,像这样
<script type="text/javascript" charset="utf-8">
var data = <?php echo json_encode($results); ?>;
</script>
请小心使用分号。 只需纠正一些JS脚本,但我认为您可以做到。
// 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,
...
xmlhttp(如果不使用jQuery)
您需要回显内容类型,以便浏览器看到返回数据并接受为json。
echo ('Content-type: application/json');
$json = json_encode($results);
echo $json;
我通常会打开Google控制台或firefox的萤火虫,以查看发送到的网络标签上的响应标签。 从那里,您可以查看要从服务器返回的数据,以检查是否回显了正确的数据。
此外,您可以通过pluggin在控制台日志中打印它们
console.log(data);
在您的JavaScript中,以确认您是否以正确的格式获取数据。
您不妨查看一些db文档来提取所需的数据。
而不是SELECT * FROM pdotable,而是SELECT期间,销售,利润。
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.