如何调用ajax函数动态更新Highcharts图?

时间:2017-04-21 10:56:05

标签: json ajax highcharts

我使用Highcharts绘制温度与时间的关系图。我有一个JSON文件,其中来自后端的数据保持更新JSON文件。我想调用ajax函数,使图表自动生成时间。怎么做?我是高级排行榜的新手,请帮助我。

1 个答案:

答案 0 :(得分:1)

您可以使用Series.addPoint方法。 http://api.highcharts.com/highcharts/Series.addPoint

以下是使用带有GET HTTP请求的实时数据的Highcharts的示例。

const options = {
  chart: {
    type: 'spline'
  },
  title: {
    text: 'Live Bitcoin Price'
  },
  xAxis: {
    type: 'datetime'
  },
  yAxis: {
    title: {
      text: 'Price (USD)'
    }
  },
  legend: {
    enabled: false
  },
  exporting: {
    enabled: false
  },
  series: [{
    name: 'Live Bitcoint Price [USD]',
    data: []
  }]
}
const chart = Highcharts.chart('container', options)

// Data
const getData = () => {
  setInterval(() => {
    window.fetch('https://api.cryptonator.com/api/ticker/btc-usd').then((response) => {
      return response.json()
    }).then((data) => {
      chart.series[0].addPoint({ x: data.timestamp * 1000, y: Number(data.ticker.price) })
    })
  }, 3000)
}
getData()
@import 'https://code.highcharts.com/css/highcharts.css';
.highcharts-background {
  fill: #222;
}

.highcharts-title,
.highcharts-axis-title {
  fill: #DDD;
}

.highcharts-credits,
.highcharts-credits:hover {
  fill: #222;
}
body {
  background-color: #222;
  margin 0 !important;
}
#container {
  margin: 0;
  padding: 0;
  border: 0;
  background-color: #222;
  min-height: 400px;
  height:95%;
  width:95%;
  position:absolute;
}
<script src="https://code.highcharts.com/highcharts.js"></script>

<div id="container"></div>

实例: https://jsfiddle.net/xpfkx91w/