无法使用chart.js创建单独的图表

问题描述 投票:0回答:1

我想显示单独的图表。当用户在页面上选择多个SensorData时,应分别显示传感器的数据。我现在得到的基本上是所谓的“多图表”,我不想要。

这是根据从Ajax POST调用返回的数据绘制图表的代码:

var visualisesensor = [];

$(document).ready(function () {
    //When the button is clicked it should add the ID's from the Sensors I want to visualise in to an array.
    $("#visualisebtn").click(function () {
        $.each($("input[name='removecheckbox']:checked"), function () {
            visualisesensor.push($(this).val());
        });

        //This is where I create multiple DIVs based upon howmany Sensors the user selected to display
        for (var i = 0; i < visualisesensor.length; i++) {
            $("#chart-container").append("<canvas id=" + visualisesensor[i] + "></canvas>");
        }

        //This is where I basically draw the charts based upon the amount of sensors the user selected
        $.ajax({
               url:     "visualise.php",
               method:  "POST",
               data:    {visualisesensor: visualisesensor},
               success: function (data) {
                   var Sensornaam = [];
                   var Temperatuur = [];

                   for (var i in data) {
                       Sensornaam.push("Sensor: " + data[i].Sensornaam);
                       Temperatuur.push(data[i].Temperatuur);
                   }
                   var chartdata = []

                   for (var k = 0; k < data.length; k++) {
                       chartdata = {
                           labels:   Temperatuur,
                           datasets: [
                               {
                                   label:                'Sensor Temperatuur',
                                   backgroundColor:      'rgba(200, 200, 200, 0.75)',
                                   borderColor:          'rgba(200, 200, 200, 0.75)',
                                   hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
                                   hoverBorderColor:     'rgba(200, 200, 200, 1)',
                                   data:                 Temperatuur[k]
                               }
                           ]
                       };
                   }

                   for (var j = 0; j < data.length; j++) {
                       var ctx = $("#" + data[j].SensorID);

                       var barGraph = new Chart(ctx, {
                           type: 'bar',
                           data: chartdata,
                       });

                       console.log(chartdata[j]);
                       alert('Chart has been added!');
                   }
               },
               error:   function (data) {
                   console.log(data);
               }
           });
    });
});

这是visualise.php代码:

<?php
//setting header to json
header('Content-Type: application/json');

include ('../DATABASE/connection.php');

if(isset($_POST["visualisesensor"]))
{
        $j = implode(',',$_POST["visualisesensor"]);

        $query = sprintf("SELECT SensorID, Sensornaam, Temperatuur FROM sensoren WHERE SensorID in ($j)");

        $result = $con->query($query);

        //loop through the returned data
        $data = array();
        foreach ($result as $row) {
            $data[] = $row;
        }

        //free memory associated with result
        $result->close();

        //close connection
        $con->close();

        //now print the data
        print json_encode($data);
}
?>

我现在得到的是一个多图表。它会成功显示数组中的数据,但仅显示在同一图表中。我希望传感器的数据分开显示。我将如何处理?

内部数据是什么:

enter image description here

数据库图片:enter image description here我得到(不想要)的输出图片:Bad Output

javascript jquery ajax chart.js
1个回答
1
投票

success调用的$.ajax函数非常奇怪;我不明白为什么data变量要重复3次。由于问题中没有提供测试数据,因此我根据代码对它们进行了逆向工程,并创建了一个简化的答案,该答案绘制了三个单独的图表:

// spoofed user input for testing.
var visualisesensor = ['1', '2'];

// spoofed ajax result data for test purposes.
var data = [{
  SensorID: '1',
  Sensornaam: 'tempsensor',
  Temperatuur: '45'
}, {
  SensorID: '2',
  Sensornaam: 'meter',
  Temperatuur: '83'
}];

for (var i = 0; i < visualisesensor.length; i++) {
  $("#chart-container").append("<canvas id=" + visualisesensor[i] + "></canvas>");
}

for (var i = 0; i < data.length; i++) {
  var ctx = $("#" + data[i].SensorID);

  var chartdata = {
    labels: [data[i].Sensornaam],
    datasets: [{
      label: 'Sensor Temperatuur',
      backgroundColor: 'rgba(200, 200, 200, 0.75)',
      borderColor: 'rgba(200, 200, 200, 0.75)',
      hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
      hoverBorderColor: 'rgba(200, 200, 200, 1)',
      data: [data[i].Temperatuur]
    }]
  };

  new Chart(ctx, {
    type: 'bar',
    data: chartdata,
    options: {
      scales: {
        yAxes: [{
          ticks: {
            beginAtZero: true
          }
        }]
      }
    }
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="chart-container"></div>
© www.soinside.com 2019 - 2024. All rights reserved.