javascript - 从同一文件获取 JSON 数据

标签 javascript php mysql json ajax

我正在尝试使用 MYSQL 数据库中的数据显示 google 图表。当我使用两个单独的文件(php/js)但我想在一个文件中处理数据时,它就可以工作。

这是我得到的:

$table = array();
        $table['cols'] = array(
            array('label' => 'Date', 'type' => 'string'),
            array('label' => 'Meter', 'type' => 'number')
        );
        $rows = array();

        $select->execute();
        while ($result = $select->fetch(PDO::FETCH_ASSOC)) {

            $timestamp = strtotime($result['date']);
            $date = date("d.m.Y - H:i", $timestamp);

            $temp = array();
            $temp[] = array('v' => $date);
            $temp[] = array('v' => $result['meter']);
            $rows[] = array('c' => $temp);
        }
        $table['rows'] = $rows;
        $json = json_encode($table);

        echo $json;

        ?>

        <html>
        <head>
            <script type="text/javascript" src="../assets/js/loader.js"></script>

            <script type="text/javascript">
                google.charts.load('current', {'packages':['corechart']});

                google.charts.setOnLoadCallback(drawChart);

                function drawChart() {
                    var jsonData = $.ajax({
                        dataType: "json",
                        async: true
                    }).responseText;

                    alert(jsonData);

                    var data = new google.visualization.DataTable(jsonData);

                    var chart = new google.visualization.LineChart(document.getElementById('chart_div2'));
                    chart.draw(data, {width: 1000, height: 240});
                }

            </script>
        </head>
        <body>
            <hr class="major" />

            <div id="chart_div2"></div>
        </body>
        </html>

PHP 数据已正确编码,但我不知道如何将数据“发送”到 javascript 部分。是否可以在同一个文件中接收 JSON 数据? 当我将 async: true 更改为 false 时,它只显示整个页面的代码,使用 true 则显示 undefined.

亲切的问候, 斯卡尔

最佳答案

当你以这种方式回显 $json 时

<?php
// ...getting data
?>
<script>
var jsonData = <?php echo $json; ?>;
</script>
<?php 
// rest of page...

稍后您可以在 javascript 中使用它,不再需要 ajax。

//....
chart.draw(jsonData, {width: 1000, height: 240});
//....

关于javascript - 从同一文件获取 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43115039/

相关文章:

javascript - 使用 Promises 对 Ember 对象数组进行排序

php - 使用 hasMany 时 Laravel Nova 404

MySQL 最后一个操作不是 'stop'

MySQL检测字段是否为空

mysql - 将单个数据库分为事件数据库和存档数据库

javascript - Firebase 匿名身份验证如何生成 UID?

javascript - rxjs 流程和 ngrx 选择器的问题

javascript - 从函数返回的数组 - TypeError : callback is not a function

php - 如何在 MySQL 中为唯一值生成唯一编号?

php - NET::ERR_CERT_DATE_INVALID 本地开发 (xampp)