我正在使用chartjs来显示来自服务器的实时流数据我已经使用ajax和php每秒获取数据,但我认为这不是最好的主意。这是我的 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,但我真的不知道我是否应该使用它,如果是,我如何在每次打开图表时连续获取数据。
米脂