如何在Javascript中访问PHP变量?

时间:2015-07-31 17:05:45

标签: javascript php codeigniter

我正在使用JavaScript和CodeIgniter制作费用饼图。

控制器

chart_c
function getchart1() {
    $result['query']=$this->model_m->getchart2();
    $this->load->view('chartview',$result);
}
model_m
function getchart2() {
    $query = $this->db->get('qpaper');
    return $query->result();
}

查看

foreach($query as $row) {
    $ex=$row->expenses;
    $cat=$row->category;
}

如何从以下JavaScript中的上述脚本中访问$row->expenses$row->category

var data = google.visualization.arrayToDataTable([
    ['Task', 'Hours per Day'],////how i will insert the data from db 
    ['Work',     11],///my doubt here $e how i will put here
    ['Eat',      2],
    ['Commute',  2],
    ['Watch TV', 2],
    ['Sleep',    7]
]);

完整代码:

<html>
    <head>
        <script type="text/javascript" src="https://www.google.com/jsapi"></script>
        <script type="text/javascript">
            google.load("visualization", "1", {packages:["corechart"]});
            google.setOnLoadCallback(drawChart);
            function drawChart() {
                var data = google.visualization.arrayToDataTable([
                    ['Task', 'Hours per Day'],////how i will insert the data from db 
                    ['Work',     11],///my doubt here $e how i will put here
                    ['Eat',      2],
                    ['Commute',  2],
                    ['Watch TV', 2],
                    ['Sleep',    7]
                ]);

                var options = {
                  title: 'My Daily Activities'
                };

                var chart = new google.visualization.PieChart(document.getElementById('piechart'));

                chart.draw(data, options);
            }
        </script>
    </head>
    <body>
        <div id="piechart" style="width: 900px; height: 500px;"></div>
    </body>
</html>

1 个答案:

答案 0 :(得分:0)

如果它只是你想要一个使用php数组的饼图,你可以使用Highcharts。检查他们在Jsfiddle页面中的编辑。您只需要在json format中传递数据即可生成图表。我想你已经有了php数组,将它转换为json格式并将其传递给这个高级函数。