duanliangman5398 2017-03-30 10:22
浏览 63
已采纳

从同一文件中获取JSON数据

i am trying to display google charts with data from a MYSQL database. It work's when i am using two seperate files (php/js) but i want to process the data in one file.

Heres what i got:

$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>

The PHP data gets encoded properly but i dont know how to "send" the data to the javascript part. Is it possible to receive the JSON data in the same file? When i change async: true to false, it just displays the code from the whole page, with true it displays undefined.

Kind regards, Skar

</div>
  • 写回答

1条回答 默认 最新

  • duan198123 2017-03-30 10:31
    关注

    when you echo the $json that way

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

    you can use it in javascript later and don't need the ajax anymore.

    //....
    chart.draw(jsonData, {width: 1000, height: 240});
    //....
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化