我正在使用chartjs來顯示來自服務(wù)器的實時流數(shù)據(jù)我已經(jīng)使用ajax和php每秒獲取數(shù)據(jù),但我認為這不是最好的主意。這是我的 javascript 代碼。 $(document).ready(function(){ $.getJSON({ url: "http://localhost/chartJS/data.php", method: "GET", success: function(data) { console.log(data); var player = []; var score = []; $.each(data, function(key, value){ player.push("Player "+value[0]); score.push(parseInt(value[1])); }); var chartdata = { labels: player, datasets : [ { label: 'Player Score', backgroundColor: 'rgba(200, 200, 200, 0.75)', borderColor: 'rgba(200, 200, 200, 0.75)', hoverBackgroundColor: 'rgba(200, 200, 200, 1)', hoverBorderColor: 'rgba(200, 200, 200, 1)', data: score } ] }; var ctx = $("#mycanvas"); var barGraph = new Chart(ctx, { type: 'line', data: chartdata }); }, error: function(data) { console.log(data); }}); updateChart();});function updateChart(){ var x=2; $(document).ready(function(){ $.getJSON({ url: "http://localhost/chartJS/data.php?x="+x, method: "GET", success: function(data) { console.log(data); var player = []; var score = []; $.each(data, function(key, value){ player.push("Player "+value[0]); score.push(value[1]); }); var chartdata = { labels: player, datasets : [ { label: 'Player Score', backgroundColor: 'rgba(200, 200, 200, 0.75)', borderColor: 'rgba(200, 200, 200, 0.75)', hoverBackgroundColor: 'rgba(200, 200, 200, 1)', hoverBorderColor: 'rgba(200, 200, 200, 1)', data: score } ] };我聽說過 websocket,但我真的不知道我是否應(yīng)該使用它,如果是,我如何在每次打開圖表時連續(xù)獲取數(shù)據(jù)。
1 回答

米脂
TA貢獻1836條經(jīng)驗 獲得超3個贊
我認為你正在尋找的是間隔:
所述的setInterval()方法調(diào)用的功能或在指定的時間間隔計算表達式(以毫秒為單位)。
例子:
setInterval(function(){ alert("Hello"); }, 3000);
它每 3 秒觸發(fā)一次警報。
因此,在您的情況下,只需在間隔內(nèi)設(shè)置一個 ajax 調(diào)用并每 1000 毫秒調(diào)用一次,然后使用新數(shù)據(jù)修改圖表。
- 1 回答
- 0 關(guān)注
- 305 瀏覽
添加回答
舉報
0/150
提交
取消