1

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ファイルは以下のようなものです。

$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をデータにハードコーディングすると正常に動作しますが、ajaxからjsonを同じjson形式で返すと、ゲージが描画されません

4

1 に答える 1

3

まずsetInterval(drawChart, 1000);、描画関数の最後に呼び出すことは、あなたがやりたいことではありません。これは、各呼び出しで(既存の間隔の上に)新しい間隔を生成するため、間隔の指数関数的な成長が得られ、毎回数が2倍になります。 2 番目 (大まかに言えば、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、ブラウザで に移動し、出力を投稿して、これをテストできるようにします。

于 2013-10-01T14:37:11.363 に答える