从ajax向动态图表添加数据

时间:2018-03-09 15:46:49

标签: javascript

我正在尝试使用我的arduino网页的动态图表。传感器值使用ajax更新到页面。但我无法使用传感器值更新图表。传感器值在变量" data_val" .once我在图表函数中调用该变量它不起作用。问题是变量data_val上的值没有达到图表的y值。但是当我为变量y指定一个数值时,它会显示指定的值。 我不熟悉java-script和ajax。所以任何人都可以帮我解决这个问题。



var data_val = 0;

function GetArduinoInputs() {
  nocache = "&nocache=" + Math.random() * 1000000;
  var request = new XMLHttpRequest();
  request.onreadystatechange = function() {
    if (this.readyState == 4) {
      if (this.status == 200) {
        if (this.responseXML != null) {
          document.getElementById("input3").innerHTML =
            this.responseXML.getElementsByTagName('analog')[0].childNodes[0].nodeValue;
          data_val = this.responseXML.getElementsByTagName('analog')[0].childNodes[0].nodeValue;
          document.getElementById("demo").innerHTML = data_val;
        }
      }
    }
  }

  request.open("GET", "ajax_inputs_one" + nocache, true);
  request.send(null);
  setTimeout('GetArduinoInputs()', 1000);
}

function gr() {
  Highcharts.setOptions({
    global: {
      useUTC: false
    }
  });

  Highcharts.chart('container', {
    chart: {
      type: 'spline',
      animation: Highcharts.svg, // don't animate in old IE
      marginRight: 10,
      events: {
        load: function() {

          // set up the updating of the chart each second
          var series = this.series[0];
          setInterval(function() {
            var y = data_val;
            var x = (new Date()).getTime(); // current time

            series.addPoint([x, y], true, true);
          }, 1000);
        }
      }
    },
    title: {
      text: 'Live random data'
    },
    xAxis: {
      type: 'datetime',
      tickPixelInterval: 150
    },
    yAxis: {
      title: {
        text: 'Value'
      },
      plotLines: [{
        value: 0,
        width: 1,
        color: '#808080'
      }]
    },
    tooltip: {
      formatter: function() {
        return '<b>' + this.series.name + '</b><br/>' +
          Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
          Highcharts.numberFormat(this.y, 2);
      }
    },
    legend: {
      enabled: false
    },
    exporting: {
      enabled: false
    },
    series: [{
      name: 'Random data',
      data: (function() {
        // generate an array of random data
        var data = [],
          time = (new Date()).getTime(),
          i;

        for (i = -19; i <= 0; i += 1) {
          data.push({
            x: time + i * 1000,

          });
        }
        return data;
      }())
    }]
  });
}
&#13;
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>

<body onLoad="gr();GetArduinoInputs()">
  <p>Motor Speed: <span id="input3">...</span> Hz</p>
  <p id="demo"></p>
  <div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
</body>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

您需要修复AJAX调用以实际获取数据。我添加了一个失败的else-block来随机分配一个值进行更新。

我还更改了一些变量和类名。

&#13;
&#13;
var currentSpeed = 0,            // Current speed
    dataFetchRate = 1000,        // Rate of data request
    refreshRate = dataFetchRate; // Rate of adding the current speed to the chart

/**
 * Returns a random integer between min (inclusive) and max (inclusive)
 * Using Math.round() will give you a non-uniform distribution!
 */
function getRandomInt(min, max) {
  if (max === undefined) { max = min; min = 0; }
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function GetArduinoInputs() {
  var nocache = "&nocache=" + getRandomInt(1000000);
  var request = new XMLHttpRequest();
  var requestUrl = 'ajax_inputs_one' + nocache;
  
  request.onreadystatechange = function() {
    if (this.readyState == 4) {
      if (this.status == 200) {
        if (this.responseXML != null) {
          var rawData = this.responseXML.getElementsByTagName('analog')[0]
                          .childNodes[0].nodeValue;
        
          currentSpeed = parseInt(rawData, 10);
        }
      } else {
        currentSpeed = getRandomInt(144); // If error, get a random number from 0 - 144
      }
      document.getElementById('current-speed').innerHTML = currentSpeed;
    }
  }

  request.open('GET', requestUrl, true);
  request.send(null);
  setTimeout(GetArduinoInputs, dataFetchRate);
}

function gr() {
  Highcharts.setOptions({
    global: {
      useUTC: false
    }
  });

  Highcharts.chart('container', {
    chart: {
      type: 'spline',
      animation: Highcharts.svg, // don't animate in old IE
      marginRight: 10,
      events: {
        load: function() {
          // set up the updating of the chart each second
          var series = this.series[0];
          setInterval(function() {
            var y = currentSpeed;
            var x = (new Date()).getTime(); // current time

            series.addPoint([x, y], true, true);
          }, refreshRate);
        }
      }
    },
    title: {
      text: 'Live random data'
    },
    xAxis: {
      type: 'datetime',
      tickPixelInterval: 150
    },
    yAxis: {
      title: {
        text: 'Value'
      },
      plotLines: [{
        value: 0,
        width: 1,
        color: '#808080'
      }]
    },
    tooltip: {
      formatter: function() {
        return '<b>' + this.series.name + '</b><br/>' +
          Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
          Highcharts.numberFormat(this.y, 2);
      }
    },
    legend: {
      enabled: false
    },
    exporting: {
      enabled: false
    },
    series: [{
      name: 'Random data',
      data: (function() {
        // generate an array of random data
        var data = [],
          time = (new Date()).getTime(),
          i;

        for (i = -19; i <= 0; i += 1) {
          data.push({
            x: time + i * 1000,

          });
        }
        return data;
      }())
    }]
  });
}
&#13;
#container {
  min-width: 310px;
  height: 400px;
  margin: 0 auto;
}
&#13;
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>

<body onLoad="gr();GetArduinoInputs()">
  <p>Motor Speed: <span id="current-speed">...</span> Hz</p>
  <div id="container"></div>
</body>
&#13;
&#13;
&#13;