无法将变量从PHP传递给JS

时间:2015-03-02 13:18:13

标签: javascript php html web

我想用PHP代码从我的MySQL服务器加载数据,然后用它来绘制带有谷歌图表的图表。问题是我无法在java脚本代码中使用从我的mysql中调用的数据。

PHP代码

  $connection = mysql_connect('127.0.0.1','root','123456');
  mysql_select_db('db_statmarket',$connection);
  $result2 = mysql_query('select sum(`How much read from customer`) as Leads, Date from monitor group by Date;',$connection) or die('cannot show tables');

在javascript代码中,我们可以看到var data = ...我希望他将成为我从数据库中查询的表。

HTML& JS代码 :     

<script type="text/javascript">
  google.setOnLoadCallback(drawChart);

  function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Year', 'Sales', 'Expenses'],
      ['2004',  1000,      400],
      ['2005',  1170,      460],
      ['2006',  660,       1120],
      ['2007',  1030,      540]
    ]);

    var options = {
      title: 'Company Performance',
      curveType: 'function',
      legend: { position: 'bottom' }
    };

    var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));

    chart.draw(data, options);
  }
</script>

需要看到输出如下: enter image description here

1 个答案:

答案 0 :(得分:3)

类似的东西:

<?php
    $connection = mysql_connect('127.0.0.1','root','123456');
    mysql_select_db('db_statmarket',$connection);
    $result2 = mysql_query('select sum(`How much read from customer`) as Leads, Date from monitor group by Date;',$connection) or die('cannot show tables');

    $json = array();
    while($row = mysql_fetch_assoc($result2)) {
        $json[] = $row;
    }
?>
<script type="text/javascript">
    var data = <?php echo json_encode($json); ?>;
    // chart code here
</script>

如果您的javascript位于.js文件中,您可以:

  1. 制作数据变量&#34; global&#34; (尽管最好将其包装在全局对象中,以便不污染全局命名空间)
  2. 使用Ajax(在这种情况下,php代码相同,但在单独的文件中只返回JSON数据)