如何根据所选日期获取图表数据(使用日期选择器过滤数据图表JS)

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

我已经尝试使用如下代码从特定日期获取所有数据:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">

<title>Try Chart</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>


<link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">


<script>
$(document).ready(function(){
$.datepicker.setDefaults({
    dateFormat: 'yy-mm-dd'
  });
  $("#firstdatepicker").datepicker();
  $("#lastdatepicker").datepicker();
  $("#filter").click(function() {
    var from_date = $("#firstdatepicker").val();
    var to_date = $("#lastdatepicker").val();
    if (from_date != '' && to_date != '') {
      console.log(from_date, to_date);
      var endpoint = '/api/data';

  $.ajax({
    method: "GET",
    url: endpoint,
    data: {
      from_date: from_date,
      to_date: to_date
    },
    success: function(data){
      console.log(data); //get all data
      //get data by fields
      var hum = [], time = [];
      for (var i=0; i<data.length; i++){
        hum.push(data[i].moisture);
        time.push(data[i].timestamp);
     }
      console.log(hum);
      console.log(time);
    //plot the chart

      var ctx = document.getElementById("moistureChart").getContext('2d');
      var moistureChart = new Chart(ctx, {
          type: 'line',
          data: {
              labels: time,
              datasets: [{
                  label: 'kelembaban',
                  data: hum,
                  backgroundColor: [
                      'rgb(68, 145, 252)'
                  ],
                  borderColor: [
                  '#331698'
                  ],
                  borderCapStyle: 'round',
                  borderWidth: 1
              }]
          },
          options: {
              reponsive: true,
              scales: {
                  yAxes: [{
                      ticks: {
                          beginAtZero:true,
                          stepSize:10
                      },
                        scaleLabel: {
                        display:     true,
                        labelString: 'kelembaban'
                    }
                  }],
                  xAxes: [{
                          display: true,
                          ticks: {
                            min: from_date,
                            max: to_date,
                          },
                        scaleLabel: {
                        display:     true,
                        labelString: 'Tanggal'
                    }
                  }]
              }
          }
      });
    },
    error: function(error_data){
      console.log(error_data)
    }
  });
} else {
  alert("Please Select Date");
}
  });    
});
</script>


</head>


<body>
<div class="container-fluid">
  <!--Breadcrumbs-->
  <ol class="breadcrumb">
    <li class="breadcrumb-item">
    </li>
    <li class="breadcrumb-item active">Charts</li>
    <li style="margin-left: 10px">
    data from <input type="text" id="firstdatepicker" name="firstdatepicker" value="2020-03-14">
    to <input type="text" id="lastdatepicker" name="lastdatepicker" value="2020-03-15">
    <input type="button" name="filter" id="filter" value="Filter" class="btn btn-info">
  </li>
  </ol>
    <div class="row"> 
      <div class="col-sm-1"></div>
        <canvas id="moistureChart" width="722" height="400">
        </canvas>
        <div class="col-sm-1"></div>
    </div>
</div>



<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.9.2/jquery.ui.datepicker.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<!--buat kalender-->
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.9.2/themes/sunny/jquery-ui.min.css"></link>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.css"></link>

</body>
</html>

数据来自我使用django rest框架制作并在本地(localhost)运行的API。数据看起来像这样:

[
{
    "id": 2,
    "timestamp": "2020-03-15T11:46:10+07:00",
    "vibration": 3,
    "moisture": 70,
    "gps_latitude": "-7.7713794",
    "gps_longitude": "110.3753111",
    "gyro_x": 6.58,
    "gyro_y": 85.0,
    "gyro_z": -3.9,
    "accelero_x": 6.58,
    "accelero_y": 85.0,
    "accelero_z": -3.9,
    "displacement": 10,
    "node_id": 1
},
{
    "id": 6,
    "timestamp": "2020-03-15T12:00:10+07:00",
    "vibration": 3,
    "moisture": 75,
    "gps_latitude": "-7.7713794",
    "gps_longitude": "110.3753111",
    "gyro_x": 6.58,
    "gyro_y": 85.0,
    "gyro_z": -3.9,
    "accelero_x": 6.58,
    "accelero_y": 85.0,
    "accelero_z": -3.9,
    "displacement": 10,
    "node_id": 1
},
{
    "id": 7,
    "timestamp": "2020-03-15T13:00:10+07:00",
    "vibration": 3,
    "moisture": 75,
    "gps_latitude": "-7.7713794",
    "gps_longitude": "110.3753111",
    "gyro_x": 6.58,
    "gyro_y": 85.0,
    "gyro_z": -3.9,
    "accelero_x": 6.58,
    "accelero_y": 85.0,
    "accelero_z": -3.9,
    "displacement": 10,
    "node_id": 1
},
{
    "id": 8,
    "timestamp": "2020-03-16T07:00:00+07:00",
    "vibration": 3,
    "moisture": 80,
    "gps_latitude": "-7.7713794",
    "gps_longitude": "110.3753111",
    "gyro_x": 6.58,
    "gyro_y": 85.0,
    "gyro_z": -3.9,
    "accelero_x": 6.58,
    "accelero_y": 85.0,
    "accelero_z": -3.9,
    "displacement": 10,
    "node_id": 1
},
{
    "id": 9,
    "timestamp": "2020-03-17T07:00:00+07:00",
    "vibration": 3,
    "moisture": 70,
    "gps_latitude": "-7.7713794",
    "gps_longitude": "110.3753111",
    "gyro_x": 6.58,
    "gyro_y": 85.0,
    "gyro_z": -3.9,
    "accelero_x": 6.58,
    "accelero_y": 85.0,
    "accelero_z": -3.9,
    "displacement": 10,
    "node_id": 1
},
{
    "id": 10,
    "timestamp": "2020-03-18T07:00:00+07:00",
    "vibration": 3,
    "moisture": 77,
    "gps_latitude": "-7.7713794",
    "gps_longitude": "110.3753111",
    "gyro_x": 6.58,
    "gyro_y": 85.0,
    "gyro_z": -3.9,
    "accelero_x": 6.58,
    "accelero_y": 85.0,
    "accelero_z": -3.9,
    "displacement": 10,
    "node_id": 1
}
]

当我选择3月15日至3月16日的日期时,图表不会显示3月15日至16日的数据,而是显示我在API中拥有的所有数据。我的代码有任何错误吗?我认为我的代码中缺少某些内容。您能帮我提供代码吗?我希望图表仅显示我在datepicker上选择的日期的数据。抱歉,我是新手程序员

javascript datepicker chart.js
1个回答
0
投票

使用基于时间的数据,您应该使用时间ChartsJS这样的方式来设置XAxe中的限制。

xAxes: [
        {
          type: "time",
          time: {
            minUnit: "minute",
            unit: "minute",
            unitStepSize: 4,
            min: moment(from_date).toDate(),//Date object type
            max: moment(to_date).toDate()//Date object type
          },
          ...
        }
      ],

注意,使用此模式时,您需要按以下方式使用数据:

{
    x: date,//Date object type
    y: value // Number
}

请注意,您的时间限制对象应该是日期对象。我建议使用momenjs库来处理日期数据,因为它具有许多兼容性。例如,从服务器检索的数据的时间戳与Safari中的构造函数Date不兼容。但您可以执行类似的操作

moment(data.timestamp).toDate()
© www.soinside.com 2019 - 2024. All rights reserved.