我有两个文件,一个从MySQL数据库输出数据,另一个用其他指标在页面中绘制Google Graph:
grab_twitter_stats.php输出:
[15, 32], [14, 55], [13, 45], [12, 52], [11, 57], [10, 55], [9, 58], [8, 42], [7, 44], [6, 40], [5, 54], [4, 52], [3, 60], [2, 71], [1, 43],
index.php输出:
<div id="curve_chart" style="width: 900px; height: 500px">
<script type="text/javascript">
google.charts.load('current', {packages: ['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Minutes', 'Tweets'],
<?php require('grab_twitter_stats.php');?>
]);
var options = {
title: 'Tweets in last 15 Minutes',
curveType: 'function',
hAxis: {
title: 'Last 15 Minutes',
direction: '-1'
},
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</div>
这会绘制一张图表,显示过去15分钟内的推文。我可以让图表出现一次,但在尝试加载SetInterval时,它不会在间隔时刷新Google图表。我试过在其中包装整个drawChart()函数,它似乎没有工作。我尝试使用AJAX,但它没有用JSON格式化,所以ajax不喜欢它。有关使此图表自动刷新的最简单方法的任何建议吗?
答案 0 :(得分:1)
虽然不是JSON,但你仍然可以使用ajax,即使是纯文本
这样的事情会让你接近......
google.charts.load('current', {
callback: function () {
drawChart();
setInterval(drawChart, (15 * 60 * 1000));
function drawChart() {
$.ajax({
url: 'grab_twitter_stats.php',
type: 'get',
success: function (txt) {
// check for trailing comma
if (txt.slice(-1) === ',') {
txt = txt.substring(0, txt.length - 1);
}
var txtData = JSON.parse('[["Minutes", "Tweets"],' + txt + ']');
var data = google.visualization.arrayToDataTable(txtData);
var options = {
title: 'Tweets in last 15 Minutes',
curveType: 'function',
hAxis: {
title: 'Last 15 Minutes',
direction: '-1'
},
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
});
}
},
packages: ['corechart']
});