在 HTTP POST 中修改 JSON 文件后,如何从 chartjs 重新加载数据

我的网页想要在图表中显示来自数据库的一些数据。我正在使用 chartjs 来绘制图表。一个 php 脚本用于生成一个 json 文件,该文件将用于绘制图表。


我想实现一个过滤器,它将根据用户输入选择一些特定的数据。输入将使用 HTTP Post 传递到 php 脚本中。之后创建的json文件没问题,但我不知道如何根据新的json文件更新图表。


<script>  

      $(document).ready(function(){  

           $('#filter').click(function(){  

                var from_date = $('#from_date').val();  

                var to_date = $('#to_date').val();  

                if(from_date != '' && to_date != '')  

                {                       

                      $.post("data.php", {

                      from_date: from_date

                      }, function(data,status) {

                      $("data").html(data);

                      });    

                }  


                else  

                {  

                     alert("Please Select Date");  

                }  

           });  

      });  

 </script> 

PHP 脚本如下所示:


if(isset($_POST["from_date"]))

{

$from = $_POST["from_date"];

$query = sprintf("SELECT * FROM Temperature 

                    WHERE Temperature > '".$from."'

                ");

}

else

{

    $query = sprintf("SELECT * FROM Temperature 

                ");

}

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


$data = array();

foreach ($result as $row) {

  $data[] = $row;

}

$result->close();

$mysqli->close();

print json_encode($data);

和 js 文件:


$(document).ready(function(){

  $.ajax({

    url: "http://localhost/chartjs/data.php",

    method: "GET",

    success: function(data) {

      console.log(data);

      var timestamp = [];

      var temperature  = [];

      var humidity = [];

      var pressure = [];


      for(var i in data) {

        timestamp.push(data[i].TimeStp);

        temperature.push(data[i].Temperature);

        humidity.push(data[i].Humidity);

        pressure.push(data[i].Pressure);

      }



json 文件在 HTTP POST 中生成得很好,但我不知道如何根据该过滤器重新绘制图表。


慕盖茨4494581
浏览 181回答 1
1回答

慕沐林林

您可以创建一个接受数据的函数。只需传递您从 POST 请求中获得的数据,就chart.update()可以发挥作用。确保在chart变量中传递图表引用。&nbsp; &nbsp; function addData(chart, label, data) {&nbsp; &nbsp; &nbsp; &nbsp; chart.data.labels.push(label);&nbsp; &nbsp; &nbsp; &nbsp; chart.data.datasets.forEach((dataset) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dataset.data.push(data);&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; chart.update();&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP