【发布时间】:2018-07-27 10:25:48
【问题描述】:
我正在努力显示从气象站收到的天气信息,以便在我的网页上显示为实时图表。我正在使用charts.js 库将从气象站获取的天气数据呈现为JSON 数据。
在代码中,函数 loadChart() 从气象站获取有关一个字段的 json 数据,即“湿度”,并将其(作为 int)传递给 dspChrt(hum) 以呈现图形。
dspChrt(hum) 方法的主要任务是渲染图形,将从 laodChrt() 接收到的数据放入一个数组中,该数组每分钟更新一次,以将其用作参数以将实时天气数据显示为折线图。
由于气象站每分钟更新一次数据,我使用 setInterval(loadChart, 60000) 方法每分钟获取更新的 json 数据。
我正在关注本教程,该教程使用我正在尝试实施的这种方法。
[Chart.js] little update example
但它不起作用。
这是我的代码:
<html>
<head>
<meta charset="utf-8">
<title>Weather Update</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<link rel="stylesheet" href="style.css">
<script>
function dspChrt(hum[]) { // to be called by loadChart() to render live chart
var ctx = document.getElementById('myChart').getContext('2d');
var N = 10;
for(i=0; i<N; i++)
hum.push(0);
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: 'Temprature',
data: [2, 29, 5, 5, 2, 3, 10],
backgroundColor: "rgba(255,153,0,0.4)"
}]
}
});
}
</script>
<script>
var myVar = setInterval(loadChart, 60000);
function loadChrt() { //fetches json data & calls dspChart() to render graph
var wData, hum;
var requestURL = 'https://cors.io/?http://api.holfuy.com/live/?s=759&pw=h1u5l4kka&m=JSON&tu=C&su=m/s'; //URL of the JSON data
var request = new XMLHttpRequest({
mozSystem: true
}); // create http request
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
wData = JSON.parse(request.responseText);
hum = wData.humidity;
console.log("wData: " + wData);
console.log("hum: " + hum);
dspChrt(hum);
}
}
request.open('GET', requestURL);
request.send(); // send the request
//dspChrt(hum);
}
</script>
</head>
<body onload="loadChart();">
<div class="container">
<h2>Weather Update</h2>
<div>
<canvas id="myChart"></canvas>
</div>
</div>
</body>
</html>
【问题讨论】: