javascript - 从服务器接收 json 数据以显示 Chart.js 图表不起作用

标签 javascript html json chart.js

我正在使用charts.js 将从气象站接收到的天气数据显示为图表。天气数据,即“温度”和“湿度”将从气象站服务器作为 json 数据接收。

我正在使用 XMLHttpRequest 方法从服务器接收 json 数据。但是,当我将 json 响应存储在变量中并在 Charts.js 的 Charts() 方法中使用它时,它不会显示任何内容。

我已经遵循了一些教程,但至少我无法弄清楚如何使用 XmlHttpRequat 方法从气象站服务器接收 json 数据。也许问题可能在于在变量中使用存储的 jason 值,然后如何使用它的 Charts 方法的“数据”。

这是我的代码:

<!DOCTYPE html>
<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() {

    var requestURL = 'http://api.holfuy.com/live/?s=101&m=JSON&tu=C&su=m/s'; //URL of the JSON data
    var request = new XMLHttpRequest();  // create http request
    request.open('GET', requestURL);  // open a new request
    request.responseType = 'json';  // setting response type to JSON type
    request.send(); // send the request                       
    request.onload = function() {
    if(request.readyState == 4 && request.status == 200){
        var wData = JSON.parse(request.responseText);
        var hum = wData.humidity;

    }  }        

    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: 'Temprature',
      data: [2, 29, 5, 5, 2, 3, 10],
      backgroundColor: "rgba(255,153,0,0.4)"
    }]
  }
});
}
    </script>


  </head>


  <body onload="dspChrt();">

  <div class="container">

  <h2>Weather Update</h2>

  <div>
    <canvas id="myChart"></canvas>
  </div>

  </div>


  </body>
</html>

编辑代码:

<!DOCTYPE html>
<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) {

    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: 'Temprature',
      data: [2, 29, 5, 5, 2, 3, 10],
      backgroundColor: "rgba(255,153,0,0.4)"
    }]
  }
});
}
    </script>

<script>

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

 function loadChart()
 {

    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);
        console.log(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>

最佳答案

使用onreadystatechange而不是onload,不要使用request.responseType = 'json';并调用open()声明 onreadystatechange 后的 send()

w3schools example

var requestURL = 'http://api.holfuy.com/live/?s=101&m=JSON&tu=C&su=m/s'; //URL of the JSON data
var wData, hum;

var request = new XMLHttpRequest(); // create http request

request.onreadystatechange = function() {
  if (request.readyState == 4 && request.status == 200) {
    wData = JSON.parse(request.responseText);
    hum = wData.humidity;

    console.log(wData);
    console.log(hum);
  }
}

request.open('GET', requestURL);
request.send(); // send the request

顺便说一句,您创建了 hum 变量来存储您在回调函数范围内收到的数据,因此当您尝试时,变量 hum 不存在创建图表。在 ajax 请求之前创建变量,然后将其填充到回调中,这样当您创建图表时该变量将具有值。

关于javascript - 从服务器接收 json 数据以显示 Chart.js 图表不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51480271/

相关文章:

php - 有什么办法可以自动触发自定义事件吗?

javascript - Angular — 屏蔽输入、$parsers、$formatters 和模式验证

html - JQM 1.4 svg 和 png 图标对于离线应用程序来说是噩梦。有什么捷径吗?

html 问题想将一个表移动到另一个表旁边

jquery - 将数据添加到动态创建的 Chart.js 数据集

json - 检查 json 数组中是否存在值

来自 JSON 数组的 mySQL WHERE IN

javascript - JSON.parse(hr.response) 错误

javascript - 如何使用 grunt 目标

php - 如何使用简单的 HTML DOM 解析器获取 <a> 标签中的 url?