包含客户端数据填充的Google Charts

时间:2015-04-22 15:17:31

标签: javascript jquery google-visualization

我一直在寻找使用实时客户端数据从Google Charts填充图表的可能性。我已经尝试过向后端发送请求的解决方案,但我希望将此方与客户端环境分开,并且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显示的表中检索数据来填充Google Charts?我想它看起来像这样:

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

有没有人尝试这种做法,甚至知道是否有可能?

感谢任何输入!

1 个答案:

答案 0 :(得分:0)

使用纯JavaScript,我们假设您在HTML DataTable中拥有以上硬编码的rows <table>

<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)
    ]);
}
...

参见演示 - &gt; http://jsfiddle.net/akLf3gL9/

注意parseInt(...)重要的是我们在第2列注入的数据实际上是数字类型,否则可视化将失败。