2013-10-01 37 views
1

我一直在試圖實時更新我的​​Google測量圖表。Google測量圖表實時更新

我的代碼如下。

<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 File如下所示。

$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格式返回JSON它不是繪製計量

回答

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在瀏覽器和後它輸出這樣我就可以進行測試。