如何在javascript中使用php变量

时间:2017-02-06 21:18:23

标签: javascript php

我意识到你不能在脚本中使用php,但我很难用SQL数据填充图表。这是代码的简化版本。我已经在这里阅读了其他确切的问题,但根本无法让它发挥作用..希望有人可以提供帮助,谢谢

<?php
    $query = mysql_query("SELECT count(green), count(amber), count(red) FROM cards");
    $myData = mysql_fetch_assoc($query);
    $green = $myData['count(green)'];
    $amber = $myData['count(amber)'];
    $red = $myData['count(red)'];
?>  
<div id="students" style="height: 250px;">
<script type="text/javascript">
    Morris.Donut({
      element: 'students',
      data: [
        {value: '<?php $green; ?>', label: 'Green'},
        {value: '<?php $amber; ?>', label: 'Amber'},
        {value: '<?php $red; ?>', label: 'Red'},
      ],
      formatter: function (x) { return x }
    }).on('click', function(i, row){
      console.log(i, row);
    });
</script>
</div>

1 个答案:

答案 0 :(得分:0)

  1. 建议使用mysql别名返回可读密钥:
  2. $query = mysql_query("SELECT count(green) as `cgreen`, count(amber) as `camber`, count(red) as `cred` FROM cards");
    
    1. 建议转义列名,表名和db名:
    2. $query = mysql_query("SELECT count(`green`) as `cgreen`, count(`amber`) as `camber`, count(`red`) as `cred` FROM `cards`");
      
      1. 如果你使用utf-8作为文件编码,很容易在php中创建一个JSON并将其传递给JS:
      2. $json = json_encode($myData);
        
        var tmpd = JSON.parse('<?=$json; ?>');
        Morris.Donut({
          element: 'students',
          data: [
            {value: tmpd.cgreen, label: 'Green'},
            {value: tmpd.camber, label: 'Amber'},
            {value: tmpd.cred, label: 'Red'},
          ],
          formatter: function (x) { return x }
        }).on('click', function(i, row){
          console.log(i, row);
        });