duanliangman5398
duanliangman5398
2017-03-30 10:22
浏览 62

从同一文件中获取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
    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});
    //....
    
    点赞 评论

相关推荐