JSON从php转换为JS文件

JSON from php into JS file

本文关键字:JS 文件 转换 php JSON      更新时间:2023-09-26

我正在尝试使用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
            });
        }
    },

如何用PHP结果中的JSON替换data : [json]

在php文件中关闭标签后,您需要编写JS部分,就像一样

<script type="text/javascript" charset="utf-8">
var data = <?php echo json_encode($results); ?>;
</script>

小心使用分号。只需要更正一点JS脚本,但我认为你可以做到。

您需要回显内容类型,以便浏览器看到返回数据并接受为json。

echo ('Content-type: application/json');
$json = json_encode($results); 
echo $json;

我通常打开谷歌控制台或firefox的firebug,查看您发送到的网络选项卡上的响应选项卡。从那里,您可以看到您从服务器返回的数据,以检查您是否响应了正确的数据。

此外,您可以通过插入在控制台日志中打印它们

console.log(data); 

在您的javascript中确认您是否获得了正确格式的数据。

您还可以查看一些数据库文档来提取所需的数据。

而不是SELECT*FROM pdotable,SELECT周期,销售,利润就可以了。

希望这能有所帮助。

// 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_encode函数

这接受一个数组作为参数,并返回一个字符串json,您可以将其插入js代码中,只需使用echo函数

js代码必须插入到php文件中,而不是外部js 中