簡體   English   中英

如何使用數據庫中的數據使我的 chart.js 動態化

[英]How can make my chart.js dynamic using data from database

我知道這幾乎是兩個問題合二為一,但我不知道我應該如何單獨提出這些問題。

  1. 如何將我的數據編輯為數據庫中的數據。
  2. 我如何編輯我的代碼,以便它按時間間隔更新。

這是我的代碼:(我試圖縮短代碼)

<canvas id="myChart"></canvas>
<?php foreach($csv->getHoejde1() as $csvmaal) { ?>
  <tr>
    <td><?= $csvmaal->Actual; ?></td> // This is the data for the chart
  </tr>
<?php } ?>

當使用var_dump();

var_dump($csvmaal->Actual);

結果string(6) "129.74"

chart.js 的腳本(使用虛擬數據)

<script src="./assets/charts/dist/Chart.js"></script>
<script>
var canvas = document.getElementById("myChart");
var ctx = canvas.getContext("2d");

var horizonalLinePlugin = {
  afterDraw: function(chartInstance) {
    var yScale = chartInstance.scales["y-axis-0"];
    var canvas = chartInstance.chart;
    var ctx = canvas.ctx;
    var index;
    var line;
    var style;

    if (chartInstance.options.horizontalLine) {
      for (index = 0; index < chartInstance.options.horizontalLine.length; index++) {
        line = chartInstance.options.horizontalLine[index];

        if (!line.style) {
          style = "rgba(169,169,169, .6)";
        } else {
          style = line.style;
        }

        if (line.y) {
          yValue = yScale.getPixelForValue(line.y);
        } else {
          yValue = 0;
        }

        ctx.lineWidth = 3;

        if (yValue) {
          ctx.beginPath();
          ctx.moveTo(0, yValue);
          ctx.lineTo(canvas.width, yValue);
          ctx.strokeStyle = style;
          ctx.stroke();
        }

        if (line.text) {
          ctx.fillStyle = style;
          ctx.fillText(line.text, 0, yValue + ctx.lineWidth);
        }
      }
      return;
    };
  }
};
Chart.pluginService.register(horizonalLinePlugin);

var data = {
  labels: ["January", "February", "March", "April", "May", "June", "July"],
  datasets: [{
    label: "My First dataset",
    fill: false,
    lineTension: 0,
    backgroundColor: "rgba(75,192,192,0.4)",
    borderColor: "rgba(75,192,192,1)",
    borderCapStyle: 'butt',
    borderDash: [],
    borderDashOffset: 0.0,
    borderJoinStyle: 'miter',
    pointBorderColor: "rgba(75,192,192,1)",
    pointBackgroundColor: "#fff",
    pointBorderWidth: 1,
    pointHoverRadius: 5,
    pointHoverBackgroundColor: "rgba(75,192,192,1)",
    pointHoverBorderColor: "rgba(220,220,220,1)",
    pointHoverBorderWidth: 2,
    pointRadius: 4,
    pointHitRadius: 10,
    data: [130, 140, 120, 125, 130, 135, 140],
  }]
};

var myChart = new Chart(ctx, {
  type: 'line',
  data: data,
  options: {
    "horizontalLine": [{
      "y": 140,
      "style": "rgba(255, 0, 0, .4)",
    }, {
      "y": 120,
      "style": "#00ffff",
    }]
  }
});

編輯:添加缺少的代碼: getHoejde1()

  public function getHoejde1()
{
    return $this->db->toList("SELECT * FROM `csvhoejde1`");
}

希望我的問題很清楚

僅供參考,我已閱讀https://www.chartjs.org/docs/latest/developers/updates.html但沒有正確理解

  1. 我如何將我的數據編輯成數據庫中的數據。

您應該制作一個單獨的php文件,以從數據庫中獲取數據,例如graph.php 從數據庫中獲取數據后, json_encode()並對其進行print()

$query = "SELECT * FROM `csvhoejde1`";
$result = mysqli_query($conn, $query);
$data = array();
foreach($result as $row){
   $data[] = $row;
}
print(json_encode($data));
  1. 我如何編輯我的代碼,以便它在時間間隔上更新。

您可以通過ajax調用和setInteval()函數來完成此操作。

現在,在chart.js ,執行以下操作:

function init(){
   $.ajax({
       type : "get",
       url : "graph.php"
       success: function(data){
          var json = JSON.parse(data);

          //remaining of your chart code goes here, add this json to data 
       }
   });
}

setInterval(init, 5000);

5000表示5秒,請將其更改為您想要的任何時間。

使用json從ajax到jquery或從php到jquery獲取數據

這是我怎么做的。

<?php
       //$sth = $db->prepare("SELECT Actual FROM `csv_1data` WHERE Name = '1) Height 130' ORDER BY FK_palle");
          // USE VALUE FROM <select><option></option></select> INSTEAD OF 1) Height 130
          $sth = $db->prepare("SELECT Actual FROM `Angle` ORDER BY Dato_ur_stillet");
          $sth->execute();
          /* Fetch all of the remaining rows in the result set */
          $result = $sth->fetchAll(PDO::FETCH_COLUMN);
          // $result = explode("@", implode(",@", $result));
          // print_r for at se resultaterne.
          echo'<pre>';
          print_r($result);
          echo'</pre>';
          $std = $db->prepare("SELECT Palle_nr FROM `Angle` ORDER BY `Dato_ur_stillet` ASC");
          $std->execute();
          /* Fetch all of the remaining rows in the result set */
          $palle = $std->fetchAll(PDO::FETCH_COLUMN);
        ?>
      <!----------------------myChart---------------------->
      <script src="./assets/charts/dist/Chart.js"></script>
    <script>



    var canvas = document.getElementById("myChart");
    var ctx = canvas.getContext("2d");

    var horizonalLinePlugin = {
      afterDraw: function(chartInstance) {
        var yScale = chartInstance.scales["y-axis-0"];
        var canvas = chartInstance.chart;
        var ctx = canvas.ctx;
        var index;
        var line;
        var style;

        if (chartInstance.options.horizontalLine) {
          for (index = 0; index < chartInstance.options.horizontalLine.length; index++) {
            line = chartInstance.options.horizontalLine[index];

            if (!line.style) {
              style = "rgba(169,169,169, .6)";
            } else {
              style = line.style;
            }

            if (line.y) {
              yValue = yScale.getPixelForValue(line.y);
            } else {
              yValue = 0;
            }

            ctx.lineWidth = 3;

            if (yValue) {
              ctx.beginPath();
              ctx.moveTo(0, yValue);
              ctx.lineTo(canvas.width, yValue);
              ctx.strokeStyle = style;
              ctx.stroke();
            }

            if (line.text) {
              ctx.fillStyle = style;
              ctx.fillText(line.text, 0, yValue + ctx.lineWidth);
            }
          }
          return;
        };
      }
    };
    Chart.pluginService.register(horizonalLinePlugin);

    var data = {
      labels: [<?php echo join($palle, ',') ?>],
      datasets: [{
        label: "My First dataset",
        fill: false,
        lineTension: 0,
        backgroundColor: "rgba(75,192,192,0.4)",
        borderColor: "rgba(51,150,255,100.2)",
        borderCapStyle: 'butt',
        borderDash: [],
        borderDashOffset: 0.0,
        borderJoinStyle: 'miter',
        pointBorderColor: "rgba(75,192,192,1)",
        pointBackgroundColor: "#fff",
        pointBorderWidth: 1,
        pointHoverRadius: 5,
        pointHoverBackgroundColor: "rgba(75,192,192,1)",
        pointHoverBorderColor: "rgba(220,220,220,1)",
        pointHoverBorderWidth: 2,
        pointRadius: 2,
        pointHitRadius: 10,
        data: [<?php echo join($result, ',') ?>],
      }]
    };

    var myChart = new Chart(ctx, {
      type: 'line',
      data: data,
      options: {
        "horizontalLine": [{
          "y": 130.75,
          "style": "rgba(255, 0, 0, .4)",
        }, {
          "y": 129.1,
          "style": "#00ffff",
        }]
      }
    });
    </script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM