dtrz17917
dtrz17917
2016-07-14 18:43

最简单的方法来自动刷新页面中嵌入的Google图表

I have two files, one outputting data from a MySQL database and one drawing a Google Graph within a page with other metrics:

grab_twitter_stats.php Output:

[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 Output:

<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>

This draws a graph that shows tweets in the last 15 minutes. I can get the graph to appear once, but upon trying to load a SetInterval, it does not refresh the Google Graph on the interval. I have tried wrapping the entire drawChart() function in it, and it doesn't seem to be working. I tried using AJAX but it is not formatted in JSON so ajax doesn't like it. Any suggestions on the easiest way to make this graph auto refresh?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dqybeh2884 dqybeh2884 5年前

    although not JSON, you can still use ajax, even with plain text

    something like this should get you close...

    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']
    });
    
    点赞 评论 复制链接分享

相关推荐