簡體   English   中英

如何在 Chart.js 中處理來自 Django Rest Framework 的數據 API

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

我在 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 的格式。 有誰知道如何修復它? 我仍然是編程的新手。 先謝謝你

我嘗試在不使用請求的情況下設置沙箱示例,並且在 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>

最重要的是將你的 hum 和 vibrate 變量設置為空數組:

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 snippet 然后運行它):

在此處輸入圖片說明

最后,發生 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