javascript - JSON从php到JS文件

标签 javascript php jquery json

我正在尝试使用 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/

相关文章:

javascript - 如何使用javascript判断页面是否在iframe中?

javascript - jqplot 荧光笔工具提示文本重叠

php - 如何修复 php 中的条件赋值错误?

php - 使用 MySQL LIMIT、OFFSET 进行分页

php - 如何在while循环中排序?

jquery - 如何应用悬停效果来显示和隐藏每个 div 上的按钮?

javascript - 如何从json中按 Angular 选择类名

javascript - 有没有一种方法可以在不定义任何属性的情况下使用 CSS 过渡?

javascript - 从外部 View 动态添加 html

javascript - li onClick 功能不起作用