简体   繁体   English

如何在 Chart.js 中处理来自 Django Rest Framework 的数据 API

[英]How to handle data API from Django Rest Framework in Chart.js

I have json data in DRF which run locally at url: http://127.0.0.1:8000/api/data/ like this :我在 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
}
]

I want to make a line chart based on all the data on field "vibration" and "moisture".我想根据字段“振动”和“水分”的所有数据制作折线图。 And i've tried it with codes like this :我已经用这样的代码试过了:

<!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>

But it doesn't work, the data doesn't appear on the chart and in the inspect element of the web page only return the last data of "vibration" and "moisture".但它不起作用,数据没有出现在图表上,并且在网页的检查元素中只返回“振动”和“水分”的最后数据。 I want all the data in "vibration" and "moisture" to be plotted on the chart, not only the last one.我希望“振动”和“水分”中的所有数据都绘制在图表上,而不仅仅是最后一个。 this is the inspect element of the webpage : inspect-element-chart I think this is happen because format of the json.这是网页的检查元素: inspect-element-chart我认为这是因为 json 的格式。 Anybody know how to fix it?有谁知道如何修复它? I am still a newbie in programming.我仍然是编程的新手。 Thank you before先谢谢你

I've tried to set up a sandbox example without using the request and having the JSON as a JS Object in the JS code.我尝试在不使用请求的情况下设置沙箱示例,并且在 JS 代码中将 JSON 作为 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>

The most important thing is to set up your hum and vibrate variables as empty arrays:最重要的是将你的 hum 和 vibrate 变量设置为空数组:

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

And then to push onto them each item's moisture and vibration property (each item is each object in your JSON array):然后将每个项目的水分和振动属性推送到它们上(每个项目都是 JSON 数组中的每个对象):

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

By this at the end of the for-loop the variables are:在 for 循环结束时,变量是:

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

Also, you had your functions calling each other but neither of the functions being invoked.此外,您的函数相互调用,但两个函数都没有被调用。

So you should have this function with arguments:所以你应该有这个带参数的函数:

function dspChrt(hum, vibrate) {

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

And don't need to then call the other function loadChart again from this as the values are already passed in - we already have them并且不需要从这里再次调用另一个函数 loadChart 因为值已经传入 - 我们已经有了它们

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

And notice this function doesn't need to return anything, we just need to call dspChart(hum, vibrate)注意这个函数不需要返回任何东西,我们只需要调用dspChart(hum, vibrate)

And finally, we need to invoke/call our loadChart() function to make this happen and the Chart to be created.最后,我们需要调用/调用我们的loadChart()函数来实现这一点并创建图表。

loadChart();

Finally, the output is this (click Show code snippet and then run it):最后,输出是这样的(点击 Show code snippet 然后运行它):

在此处输入图片说明

And so finally, the code with the XMLHttpRequest happening is the following, but it obviously won't work on Stack Overflow:最后,发生 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM