Google Gauge Charts实时更新

时间:2013-10-01 09:21:18

标签: ajax json google-visualization

我一直在尝试实时更新我的​​Google Gauge图表。

我的守则如下。

<script type='text/javascript'>
      google.load('visualization', '1', {packages:['gauge']});
      google.setOnLoadCallback(drawChart);
      function drawChart() {

      var json = $.ajax({
                    url: 'graph.php', // make this url point to the data file
                    dataType: 'json',
                    async: false
                }).responseText;
                //alert(json);
        var data = google.visualization.arrayToDataTable(json);
        var options = {
          width: 400, height: 120,
          redFrom: 0, redTo: 3,
          greenFrom:<?php echo $inactivecount['inactive_count']-3;?>, greenTo: <?php echo $inactivecount['inactive_count'];?>,
          minorTicks: 0,
          min:0,
          max:<?php echo $inactivecount['inactive_count'];?>,
          'majorTicks': ["",""],
          'animation.duration':100
        };

        var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
        //setInterval(drawChart(12,10),1000);
        chart.draw(data, options);

        setInterval(drawChart, 1000);
      }
    </script>

Ajax文件如下所示。

$table = array();
$table=array(0=>array('Label','Value'),1=>array('Likes',$like));
// encode the table as JSON
$jsonTable = json_encode($table);

// set up header; first two prevent IE from caching queries
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Oct 2013 05:00:00 GMT');
header('Content-type: application/json');

// return the JSON data
echo $jsonTable;

如果在数据中对json进行硬编码然后它工作正常但是当我以相同的json格式从ajax返回json时它没有绘制标尺

1 个答案:

答案 0 :(得分:3)

首先,在绘制函数结束时调用setInterval(drawChart, 1000);不是你想要做的 - 这会在每次调用时产生一个新的间隔(在现有的间隔之上),所以你得到一个指数间隔的增长,每秒加倍的数字(粗略地说 - 考虑到代码的AJAX调用和执行时间,它会更长一些)。这将快速锁定您的浏览器和/或用传入的请求压倒您的服务器。试试这个:

function drawChart() {
    var data;
    var options = {
        width: 400,
        height: 120,
        redFrom: 0,
        redTo: 3,
        greenFrom: <?php echo $inactivecount['inactive_count']-3;?>,
        greenTo: <?php echo $inactivecount['inactive_count'];?>,
        minorTicks: 0,
        min: 0,
        max: <?php echo $inactivecount['inactive_count'];?>,
        majorTicks: ["",""],
        animation: {
            duration: 100
        }
    };

    var chart = new google.visualization.Gauge(document.getElementById('chart_div'));

    function refreshData () {
        var json = $.ajax({
            url: 'graph.php', // make this url point to the data file
            dataType: 'json',
            async: false
        }).responseText;

        data = google.visualization.arrayToDataTable(json);

        chart.draw(data, options);
    }

    refreshData();
    setInterval(refreshData, 1000);
}

如果这不起作用,请转到浏览器中的graph.php并发布输出的内容,以便对此进行测试。