循环使用Javascript无法正常工作

时间:2015-11-22 22:57:22

标签: javascript php jquery

请帮忙。

塞纳里奥:

我正在做一个PHP项目,它读取数据库中的数据并使用图表或图形显示它。

问题:

但问题是,当我在Javascript中执行for循环时,它无效。帮助我。

这是我的Javascript代码:

<script>
  $(function () {
    /* ChartJS
     * -------
     * Here we will create a few charts using ChartJS
     */
    //-------------
    //- PIE CHART -
    //-------------
    // Get context with jQuery - using jQuery's .get() method.

    var pieChartCanvas = $("#pieChart").get(0).getContext("2d");
    var pieChart = new Chart(pieChartCanvas);

    var PieData = [
       {
           <?php for($i=1;$i<$num_rows;$i++){  ?>

       {
            value: <?php echo $qtys[$i];?>,
            color: "#d2d6de",
            highlight: "#d2d6de",
            label: "<?php echo $items[$i];?>"
       }
       <?php } ?>
 ];
 pieChart.Doughnut(PieData, pieOptions);
 });
</script>

这是我的PHP文件:

<?php
    $num_rows = mysql_num_rows($result);
    echo $num_rows;
    $items=array();
    $qtys=array();
    while($row = mysql_fetch_array( $result)) {

        $this->stock_id = $row["id_barang"];
        $this->type = $row["jenis_barang"];
        $items[]=$this->type;
        $this->quantity = $row["kuantiti"];
        $qtys[]=$this->quantity;
        $this->weight = $row["berat"];
        $this->category = $row["kategori"];
        $this->supplier_id = $row["id_pembekal"];
   }
?>

HTML文件:

<div class="col-md-6">
      <!-- DONUT CHART -->
          <div class="box box-primary">
            <div class="box-header with-border">
              <h3 class="box-title">Donut Chart</h3>
              <div class="box-tools pull-right">
                <button class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
                <button class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
              </div>
            </div>
            <div class="box-body">
            <div class="chart">
                <canvas id="pieChart" style="height:250px"></canvas>
            </div>
            </div><!-- /.box-body -->
          </div><!-- /.box -->
    </div>

2 个答案:

答案 0 :(得分:0)

您似乎遇到语法错误:

    var PieData = [



      { // <------------------------------------------
<?php for($i=1;$i<$num_rows;$i++){  ?>

      {
        value: <?php echo $qtys[$i];?>,
        color: "#d2d6de",
        highlight: "#d2d6de",
        label: "<?php echo $items[$i];?>"
      }
    <?php } ?>

答案 1 :(得分:0)

正如莱昂所说,你需要删除你需要删除的php循环之前的额外{,但还有其他的东西。您需要使用逗号分隔大括号内的项目。有很多方法可以做到这一点,但我通常使用的方法是将每个项目作为一个字符串放在一个数组中然后内爆它们。我要做的就是这个:

<?php
$data = array();
for($i=0;$i<$num_rows;$i++){ // (you need the element number 0 as well...)
$str = '
   {
    value: '.$qtys[$i].',
    color: "#d2d6de",
    highlight: "#d2d6de",
    label: "'.$items[$i].'"
  }';
$data[] = $str;
?>

var PieData = [
<?php
echo implode(",", $data);
?>
];
相关问题