2012-12-06 61 views
0

IM完全現在困在這裏小時重繪Highcharts餅圖,我無法找到錯誤:(使用JSON數據

我需要繪製從數據餅圖我從數據庫中獲取。圖表需要每隔幾秒鐘重新繪製新的數據,以便通過AJAX獲取數據(如JSON)。目前沒有問題。

但是現在我需要讓Highcharts實際繪製新的數據。看起來不可能:(它只是停留與初始數據 - 即使警報顯示新數據已被正確解析並輸入到圖表的「數據」屬性中。

can anyo ne請指教?

<html> 
<head> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
    <script src="http://code.highcharts.com/highcharts.js"></script> 
    <script src="http://code.highcharts.com/modules/exporting.js"></script> 
    <script> 
var chart; 

var options = { 
    chart: 
    { 
     renderTo: 'container', 
     defaultSeriesType: 'column', 
     events: 
     { 
      load: requestData, 
      redraw: function(){alert("graph has just been redrawn");} 
     } 
    }, 
    series: [ 
    { 
     type: 'pie', 
     name: 'x', 
     data: [['All', 1],['more', 2]] 
    }] 
}; 

function requestData() 
{ 
    $.ajax(
    { 
     url: "http://1.2.3.4/getMeSomeJSON.php", 
     type: "GET", 
     success: function(response) 
     { 
      var json = jQuery.parseJSON(response); 
      var protocols = response.services.protocols; 

      chart.series[0].data = []; 
      for(var i=0; i<protocols.length; i++) 
      { 
       var tmp = protocols[i].prot; 
       chart.series[0].data.push({tmp: protocols[i].byte_len}); 
      } 
      //alert(chart.series[0].data); // everything seems to be OK here... 

      // neither one works :(
      //chart.redraw(); 
      //chart = new Highcharts.Chart(options); 

      // call it again after one second 
      setTimeout(requestData, 1000); 
     }, 
     cache: false 
    }); 
} 
    </script> 
</head> 
<body> 

<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto; border: 1px solid black;"></div> 
<script> 
$(document).ready(function() 
{ 
    chart = new Highcharts.Chart(options); 
}); 
</script> 
</body> 
</html> 

回答

2

要動態更新,必須使用setData,如下所示。

var json = jQuery.parseJSON(response), 
    protocols = json.services.protocols, 
    data = []; 

for(var i=0; i<protocols.length; i++) { 
    var tmp = protocols[i].prot; 
    data.push({tmp: protocols[i].byte_len}); 
} 

chart.serie[0].setData(data); 

demo

Here你可以看到一個相關的問題。

參考