获取JSON始终抛出“results.packets”未定义

时间:2017-05-26 12:00:33

标签: javascript jquery json chart.js

我目前正在设置(修改)javascript以从json文件中读取并提供这些数据chart.js,以便它可以从中创建折线图。我发现大部分脚本都在互联网上,因为我对javascript知之甚少。但无论我做什么,我总是在Firefox开发控制台中得到错误:“TypeError:results.packets is undefined”并且它也没有显示图表。

html文件如下所示:

    <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="apple-mobile-web-app-capable" content="yes"/>
    <meta name="viewport" content="initial-scale = 1.0, user-scalable = no"/>
    <meta name="apple-mobile-web-app-status-bar-style" content="default"/>
    <link rel="apple-touch-icon" href="apple-touch-icon.png" size="152x152"/>
    <script type="text/javascript" src="http://ff.kis.v2.scr.kaspersky-labs.com/B6425F5E-BD4E-014C-ADAC-6328369D0625/main.js" charset="UTF-8"></script><link rel="stylesheet" crossorigin="anonymous" href="http://ff.kis.v2.scr.kaspersky-labs.com/5260D9638236-CADA-C410-E4DB-E5F5246B/abn/main.css"/><script src="js/Chart.min.js"></script>
    <script src="js/jquery-3.2.1.min.js"></script> <!--Optional-->

    <body>
        <canvas id="myChart" width="740" height="200"></canvas>
    </body>
<script>
  function drawLineChart() {

    // Add a helper to format timestamp data
    Date.prototype.formatMMDDYYYY = function() {
        return (this.getMonth() + 1) +
        "/" +  this.getDate() +
        "/" +  this.getFullYear();
    }

    var jsonData = $.ajax({
      url: 'http://192.168.178.40/heating/vbus-server?format=json&timespan=-24 hours',
      dataType: 'json',
    }).done(function (results) {

      // Split timestamp and data into separate arrays
      var labels = [], data=[];
      results["packets"].forEach(function(packet) {
        labels.push(new Date(packet.timestamp).formatMMDDYYYY());
        data.push(parseFloat(packet.payloadString));
      });

      // Create the chart.js data structure using 'labels' and 'data'
      var tempData = {
        labels : labels,
        datasets : [{
            fillColor             : "rgba(151,187,205,0.2)",
            strokeColor           : "rgba(151,187,205,1)",
            pointColor            : "rgba(151,187,205,1)",
            pointStrokeColor      : "#fff",
            pointHighlightFill    : "#fff",
            pointHighlightStroke  : "rgba(151,187,205,1)",
            data                  : data
        }]
      };

      // Get the context of the canvas element we want to select
      var ctx = document.getElementById("myLineChart").getContext("2d");

      // Instantiate a new chart
      var myLineChart = new Chart(ctx).Line(tempData, {
        //bezierCurve: false
      });
    });
  }

  drawLineChart();
</script>

</html>

0 个答案:

没有答案