【问题标题】:Connecting Chart.js to MySQL database将 Chart.js 连接到 MySQL 数据库
【发布时间】:2015-04-23 12:28:52
【问题描述】:

我的 html 文档中有这个脚本,它使用 Chart.js 创建图表。其中的数据是手动插入的(标签和数据集中的数据)。数据集中的数据现在是随机生成的数字。但我需要以某种方式将它与我的 MySQL 数据库连接起来。

<script>
   var randomScalingFactor = function(){ return Math.round(Math.random()*100)};
   var barChartData = {
       labels : ["January","February","March","April","May","June","July","January","February","March","April","May","June","July"],
       datasets : [
          {
           fillColor : "rgba(23, 158, 3, 0.8)",
           strokeColor : "rgba(24, 107, 2, 0.8)",
           highlightFill: "rgba(24, 107, 2, 0.9)",
           highlightStroke: "rgba(24, 107, 2, 1)",
           data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
           }
           ]
   }
window.onload = function(){
     var ctx2 = document.getElementById("canvas2").getContext("2d");
     ctx2.canvas.width = 1000;
     ctx2.canvas.height = 800;
     window.myBar = new Chart(ctx2).Bar(barChartData, {
            responsive : true
     });
}

我在模型中调用选择查询,然后将结果发送到我的视图。 然后在我的视图中,我可以像这样获取我的数据。 我以表格为例。

 <?php foreach ($this->list_excercise as $value) : ?>
                  <td><?= $value['data'] ?></td>
                  <td><?= $value['label'] ?></td>
 <?php endforeach; ?>

所以数据可以像这样插入到html中,但是如何将它插入到chart.js javascript中?所以而不是

labels: ["January", "February"]

我会有类似的东西

labels: $array

我想不出一种简单的方法将数据传输到脚本中。谁能帮我解决这个问题?提前谢谢你。

【问题讨论】:

    标签: javascript php mysql chart.js


    【解决方案1】:

    如果您的数据在一个 php 数组中,而您的标签在另一个 php 数组中,那么您可以使用 json_encode 函数将您的数据传递给 chartjs。

    使用您的 $this->list_excercise 您可以这样做:

    <?php
        $data = array();
        $label = array();
        foreach ($this->list_excercise as $value) :
            $data[] = $value['data'];
            $label[] = $value['label'];
        endforeach;
    ?>
    

    然后在您的视图/模板中:

    var barChartData = {
       labels : <?php echo json_encode($label) ?>,
       datasets : [
          {
           fillColor : "rgba(23, 158, 3, 0.8)",
           strokeColor : "rgba(24, 107, 2, 0.8)",
           highlightFill: "rgba(24, 107, 2, 0.9)",
           highlightStroke: "rgba(24, 107, 2, 1)",
           data : <?php echo json_encode($data) ?>
         }
       ]
    }
    

    我还没有运行代码,但这个想法是作为 sn-p 存在的。
    看看有没有帮助。

    【讨论】:

      猜你喜欢
      • 2018-01-22
      • 2022-01-01
      • 2016-02-14
      • 2015-02-06
      相关资源
      最近更新 更多