如何将整数变量从PHP传递到Javascript Google Chart API


How to pass integer variables from PHP to a Javascript Google Chart API?

我有以下代码:

<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([
      ['Polarity', 'Percentage'],
      ['positive',     0],
      ['negative',      0],
      ['neutral',  0]
    ]);
    var options = {
      title: 'Sentiment Chart',
      is3D: true,
    };
    var chart = new google.visualization.PieChart(document.getElementById('piechart'));
    chart.draw(data, options);
  }
</script>
</head>
<body>
<?php
$positive = 20;
$negative = 30;
$neutral = 50;
echo "<div id='"piechart'" style='"width: 900px; height: 500px;'"></div>";
?>
</body>
</html>

这是一个谷歌饼图。如何将 PHP 变量$positive、$negative和$neutral传递给图表中的"正"、"负"和"中性"标签,使其在图表上分别显示 20%、30% 和 50% 的值?

我已经搜索了SO,但没有找到一个简单的方法。

把你的php放在文档的顶部,然后像这样将变量回显到javascript上:

 var data = google.visualization.arrayToDataTable([
  ['Polarity', 'Percentage'],
  ['positive',     <?php echo $positive ?>],
  ['negative',      <?php echo $negative ?>],
  ['neutral',  <?php echo $neutral ?>]
]);

只需将它们输出到它们需要的位置:

<?php echo $negative; ?>

在您的情况下可能是这样的:

<script type="text/javascript">
  google.load("visualization", "1", {packages:["corechart"]});
  google.setOnLoadCallback(drawChart);
  function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Polarity', 'Percentage'],
      ['positive',     <?php echo $positive; ?>],
      ['negative',      <?php echo $negative; ?>],
      ['neutral',  <?php echo $neutral; ?>]
    ]);
    var options = {
      title: 'Sentiment Chart',
      is3D: true,
    };
    var chart = new google.visualization.PieChart(document.getElementById('piechart'));
    chart.draw(data, options);
  }
</script>

通过在代码之前加载 PHP 并打开代码中的标签:

    <?php
    $positive = 20;
    $negative = 30;
    $neutral = 50;
    ?>
<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([
          ['Polarity', 'Percentage'],
          ['positive',     <?php echo $positive; ?>],
          ['negative',      <?php echo $negative; ?>],
          ['neutral',  <?php echo $neutral; ?>]
        ]);
        var options = {
          title: 'Sentiment Chart',
          is3D: true,
        };
        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>