2015-04-22 49 views
0

我一直在尋找利用實時客戶端數據從谷歌圖表填充圖表的可能性。我嘗試過向後端發送請求的解決方案,但我希望將此端與客戶端環境分開,並且API目前仍在開發中。帶有客戶端數據填充的谷歌圖表

這是一個標準的餅圖

//JS Code 
<script type="text/javascript" src="https://www.google.com/jsapi"></script> 
<script type="text/javascript"> 

    // Load the Visualization API and the piechart package. 
    google.load('visualization', '1.0', {'packages':['corechart']}); 

    // Set a callback to run when the Google Visualization API is loaded. 
    google.setOnLoadCallback(drawChart); 

    // Callback that creates and populates a data table, 
    // instantiates the pie chart, passes in the data and 
    // draws it. 
    function drawChart() { 

     // Create the data table. 
     var data = new google.visualization.DataTable(); 
     data.addColumn('string', 'Topping'); 
     data.addColumn('number', 'Slices'); 
     data.addRows([ 
      ['Mushrooms', 3], 
      ['Onions', 1], 
      ['Olives', 1], 
      ['Zucchini', 1], 
      ['Pepperoni', 2] 
     ]); 

     // Set chart options 
     var options = {'title':'How Much Pizza I Ate Last Night', 
      'width':400, 
      'height':300}; 

     // Instantiate and draw our chart, passing in some options. 
     var chart = new google.visualization.PieChart(document.getElementById('chart_div')); 
     chart.draw(data, options); 
    } 
</script> 
//HTML Code 
<div id="chart_div"></div> 

示例代碼有沒有辦法從正在顯示與jQuery甚至純JavaScript表中檢索數據來填充谷歌圖表?我想這將是這個樣子:

data.addRows([ 
      [$('#textfield1').getAttribute('value'), 3], 
      [$('#textfield2').getAttribute('value'), 1], 
      [$('#textfield3').getAttribute('value'), 1], 
      [$('#textfield4').getAttribute('value'), 1], 
      [$('#textfield5').getAttribute('value'), 2] 
     ]); 

有沒有人有經驗,在嘗試此,甚至不知道它是否有可能?

欣賞任何輸入!

回答

0

使用純JavaScript,讓我們假設你已經在HTML <table>上述硬編碼DataTablerows

<table id="table"> 
    <thead> 
     <tr> 
      <th>topping</th> 
      <th>slices</th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr><td>Mushrooms</td><td>3</td></tr> 
     <tr><td>Onions</td><td>1</td></tr> 
     <tr><td>Olives</td><td>1</td></tr> 
     <tr><td>Zucchini</td><td>1</td></tr> 
     <tr><td>Pepperoni</td><td>2</td></tr> 
    </tbody> 
</table>  

然後你就可以讀取表,並把它作爲圖表DataTable這樣一個來源:

... 
data.addColumn('string', 'Topping'); 
data.addColumn('number', 'Slices'); 

var tableRows = document.querySelectorAll('#table tbody tr'); 
for (var i=0;i<tableRows.length;i++) { 
    data.addRow([ 
     tableRows[i].cells[0].textContent, 
     parseInt(tableRows[i].cells[1].textContent) 
    ]); 
} 
... 

觀看演示 ​​- >http://jsfiddle.net/akLf3gL9/

注意事項parseInt(...)重要的是,我們在#2列注入的數據實際上是typeof數字,否則可視化將失敗。

+0

感謝您的回覆!它像一個魅力。 –