【问题标题】:Receiving json data from a server to display a chart.js graph not working从服务器接收 json 数据以显示 chart.js 图形不起作用
【发布时间】:2018-12-30 23:49:50
【问题描述】:

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

我正在使用 XMLHttpRequest 方法从服务器接收 json 数据。但是当我将 json 响应存储在一个变量中并在 chart.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>

【问题讨论】:

  • 您是否测试过返回的 JSON 不是 null/预期的结构?至少这样你就会知道问题出在数据上还是渲染它的图形上。
  • request.onreadystatechange = function() { if (this.readyState == 4 &amp;&amp; this.status == 200){ var wData = JSON.parse(this.responseText); var hum = wData.humidity; } } 试试这样。 [w3schools.com/xml/ajax_xmlhttprequest_response.asp]。顺便说一句,在打开和发送请求之前创建onreadystatechange函数。
  • 返回对象的湿度属性的对象类型是什么?
  • 它是一个实数或浮点值。
  • @Jay Gould:我还没有测试过,但我也在考虑。并在使用前找到一些方法来测试它。虽然在某些教程中,这是在解析后从 json 对象中获取值的方式。

标签: javascript html json chart.js


【解决方案1】:

使用onreadystatechange而不是onload,不要使用request.responseType = 'json';,并在声明onreadystatechange后调用open()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 请求之前创建变量,然后在回调中填充它,这样当您创建图表时变量将具有值。

【讨论】:

  • 它在控制台上引发此错误:跨域请求被阻止:同源策略不允许读取api.holfuy.com/live/?s=101&m=JSON&tu=C&su=m/s 的远程资源。 (原因:CORS 标头“Access-Control-Allow-Origin”缺失)。
  • 我在 SO 帖子中使用了这种方法,“或者,要尝试一下,您可以在 URL 前面加上 cors.io :' stackoverflow.com/questions/46785318/… 它删除了错误,但没有显示任何值的嗡嗡声
  • 在console.log中,它显示了Wdata中json对象的所有值和hum中的湿度值,虽然没有用hum数据填充图形。
  • @Nikko 它没有用数据填充图表,因为您在收到数据之前初始化图表之前。您必须将图形初始化放在一个函数中,并在 request.onreadystatechange 中调用该函数
  • 我在这个函数中保留了图形代码,并声明了另一个包含request.onreadystatechange的函数来调用图形显示函数。但它引发了这个错误:TypeError: 48.6 is not a non-null object[Learn More] Chart.min.js:12:2901 TypeError: l._view is undefined[Learn More] 其中 48.6 是当前的哼声值。我将编辑后的代码放在 OP 中的 EDITED CODE 中。请看这个
猜你喜欢
  • 1970-01-01
  • 2018-02-04
  • 2016-11-20
  • 2017-12-14
  • 2020-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多