【问题标题】:How to handle data API from Django Rest Framework in Chart.js如何在 Chart.js 中处理来自 Django Rest Framework 的数据 API
【发布时间】:2020-06-28 14:51:04
【问题描述】:

我在 DRF 中有 json 数据,它们在 url:http://127.0.0.1:8000/api/data/ 本地运行,如下所示:

[
{
    "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
}
]

我想根据字段“振动”和“水分”的所有数据制作折线图。我已经用这样的代码试过了:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Try Chart</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script>

<script>
function dspChrt(hum, vibrate) {
    hum = loadChart().hum;
    vibrate = loadChart().vibrate;

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'],
datasets: [{
  label: 'Humidity',
  data: hum, // json value received used in method
  backgroundColor: "rgba(153,255,51,0.4)"
}, {
  label: 'Vibration',
  data: vibrate,
  backgroundColor: "rgba(255,153,0,0.4)"
}]
}
});
}
</script>

<script>
var myVar = setInterval(loadChart, 60000); // updates chart every one minute

function loadChart()
{
var data, hum, vibrate;
var requestURL = 'http://127.0.0.1:8000/api/data'; //URL of the JSON data
var request = new XMLHttpRequest({mozSystem: true}); // create http request

request.onreadystatechange = function() {
 if(request.readyState == 4 && request.status == 200) {
    data = JSON.parse(request.responseText);
    for (var i=0; i<data.length;i++) {
        hum = data[i].moisture;
        vibrate = data[i].vibration;
    }
    console.log('hum', hum);
    console.log('vibrate', vibrate);
    console.log('data', data);
    return data,hum,vibrate;
    dspChrt(hum, vibrate);            
}
}
request.open('GET', requestURL);
request.send(); // send the request
}
</script>

</head>

<body onload="loadChart()">
<div class="container">
<h2>Try Chart</h2>
<div>
<canvas id="myChart"></canvas>
</div>
</div>
</body>
</html>

但它不起作用,数据没有出现在图表上,并且在网页的检查元素中只返回“振动”和“水分”的最后一个数据。我希望将“振动”和“水分”中的所有数据绘制在图表上,而不仅仅是最后一个。 这是网页的检查元素: inspect-element-chart 我认为这是因为 json 的格式而发生的。有人知道如何解决吗?我仍然是编程的新手。之前谢谢你

【问题讨论】:

  • 是 DRF - Django Rest 框架吗?您预计每分钟数据会发生什么变化?服务器上是否有数据记录器或其他东西?看看我的回答,希望对你有所帮助。
  • @AlexL 是的,它是 Django Rest 框架。我希望图表每分钟刷新一次并添加新数据。还没有服务器,我还是用localhost
  • @AlexL 顺便说一句,它有效!谢谢!
  • 太棒了!很高兴听到!

标签: javascript arrays json django-rest-framework chart.js


【解决方案1】:

我尝试在不使用请求并将 JSON 作为 JS 代码中的 JS 对象的情况下设置沙盒示例。

const JSONdata = [
{
    "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
}
]
function dspChrt(hum, vibrate) {

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'],
datasets: [{
  label: 'Humidity',
  data: hum, // json value received used in method
  backgroundColor: "rgba(153,255,51,0.4)"
}, {
  label: 'Vibration',
  data: vibrate,
  backgroundColor: "rgba(255,153,0,0.4)"
}]
}
});
}

// Not sure how this is expected to work? Is the Data a Stream?
//var myVar = setInterval(loadChart, 60000); // updates chart every one minute

function loadChart(){
  var data, hum = [], vibrate = [];
  
/*doing it with the JSON already in the JS for this example:

  var requestURL = 'http://127.0.0.1:8000/api/data'; //URL of the JSON data
  var request = new XMLHttpRequest({mozSystem: true}); // create http request  

  request.onreadystatechange = function() {
   if(request.readyState == 4 && request.status == 200) {
      data = JSON.parse(request.responseText);
*/    
      data = JSONdata;
      for (var i=0; i<data.length;i++) {
          hum.push(data[i].moisture);
          vibrate.push(data[i].vibration);
      }
      /*
      console.log('hum', hum);
      console.log('vibrate', vibrate);
      console.log('data', data);
      */      
      dspChrt(hum, vibrate);            
/*doing it with the JSON already in the JS for this example:       
    }
  } 
request.open('GET', requestURL);
request.send(); // send the request
*/
}
loadChart();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Try Chart</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script>
</head>
<body onload="loadChart()">
<div class="container">
<h2>Try Chart</h2>
<div>
<canvas id="myChart"></canvas>
</div>
</div>
</body>
</html>

最重要的是将你的哼声和振动变量设置为空数组:

function loadChart(){
      var data, hum = [], vibrate = [];
      ...
}

然后将每个项目的湿度和振动属性推到它们上(每个项目都是 JSON 数组中的每个对象):

for (var i=0; i<data.length;i++) {
      hum.push(data[i].moisture);
      vibrate.push(data[i].vibration);
}

在for循环结束时,变量是:

hum = [70, 75, 75, 80]
vibrate = [3, 3, 3, 3]

此外,您的函数相互调用,但没有一个函数被调用。

所以你应该有这个带参数的函数:

function dspChrt(hum, vibrate) {

    var ctx = document.getElementById('myChart').getContext('2d');
    ...
}

并且不需要从这里再次调用另一个函数 loadChart,因为值已经传入 - 我们已经有了它们

function loadChart(){
      var data, hum = [], vibrate = [];
      ...
          /*
          console.log('hum', hum);
          console.log('vibrate', vibrate);
          console.log('data', data);
          */      
          dspChrt(hum, vibrate); 
      ...
}

注意这个函数不需要返回任何东西,我们只需要调用dspChart(hum, vibrate)

最后,我们需要调用/调用我们的loadChart() 函数来实现这一点并创建图表。

loadChart();

最后输出是这样的(点击Show code sn -p 然后运行):

最后,发生 XMLHttpRequest 的代码如下,但它显然不适用于 Stack Overflow:

function dspChrt(hum, vibrate) {

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'],
datasets: [{
  label: 'Humidity',
  data: hum, // json value received used in method
  backgroundColor: "rgba(153,255,51,0.4)"
}, {
  label: 'Vibration',
  data: vibrate,
  backgroundColor: "rgba(255,153,0,0.4)"
}]
}
});
}

function loadChart(){
  var data, hum = [], vibrate = [];
  
  var requestURL = 'http://127.0.0.1:8000/api/data'; //URL of the JSON data
  var request = new XMLHttpRequest({mozSystem: true}); // create http request  

  request.onreadystatechange = function() {
   if(request.readyState == 4 && request.status == 200) {
      data = JSON.parse(request.responseText);
      //data = JSONdata;
      for (var i=0; i<data.length;i++) {
          hum.push(data[i].moisture);
          vibrate.push(data[i].vibration);
      }
      /*
      console.log('hum', hum);
      console.log('vibrate', vibrate);
      console.log('data', data);
      */      
      dspChrt(hum, vibrate);                
    }
  } 
request.open('GET', requestURL);
request.send(); // send the request

}

loadChart();
//var myVar = setInterval(loadChart, 60000); // updates chart every one minute
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Try Chart</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script>
</head>
<body onload="loadChart()">
<div class="container">
<h2>Try Chart</h2>
<div>
<canvas id="myChart"></canvas>
</div>
</div>
</body>
</html>

【讨论】:

    猜你喜欢
    • 2019-09-12
    • 2019-03-22
    • 2020-07-14
    • 2020-06-25
    • 2021-09-13
    • 1970-01-01
    • 2016-10-28
    • 2015-05-11
    • 2018-11-05
    相关资源
    最近更新 更多