首页 > 解决方案 > 用 ajax 填充谷歌可视化表

问题描述

我正在尝试将一些数据从我的网络 api 加载到谷歌表中。

所以我的 web api 返回了正确的数据。它返回 2 列数据,名称(字符串)和分数(双精度)。

我想用这些数据填充谷歌表,但不太明白如何去做。我还想在添加数据之前指定列名称和类型。

以下是我迄今为止的尝试。任何帮助都会很棒。

我在最底部包含了一个加载表格的工作示例,但是数据是硬编码的。

<!DOCTYPE html>
<html>
<head>
    <title>QES</title>
    <meta charset="utf-8" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>


 <div id="tableScore"></div>


<script type="text/javascript">
    $(document).ready(function()
    {
        google.charts.load('current', {'packages':['table']});
        google.charts.setOnLoadCallback(drawTable);

        function DrawTable() {

            var options = { title: 'Top Scores', showRowNumber: true, width: '75%', height: '75%' };

            $.ajax({
                type: 'GET',
                url: 'api/Score',
                dataType: 'json',
                success: function (data) {
                    $.ajax({

                        var arrValues = {['Name', 'Score']};

                        $.each(data, function(){
                           arrValues.push(data.Name, data.Score);
                        });
                }
            });

            var table = new google.visualization.Table(document.getElementById('tableScore'));
            table.draw(arrValues, options);
        };
      });
</script>



</body>
</html>

有效的静态数据版本

  <script type="text/javascript">
  google.charts.load('current', {'packages':['table']});
  google.charts.setOnLoadCallback(drawTable);

  function drawTable() {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Name');
    data.addColumn('number', 'Score');

    data.addRows([
      ['Tom',  2.5],
      ['Jack', 8.5]
    ]);

    var table = new google.visualization.Table(document.getElementById('tblScore'));

    table.draw(data, {showRowNumber: true, width: '75%', height: '75%'});
  }
</script>

标签: javascriptjqueryajaxgoogle-apigoogle-visualization

解决方案


推荐阅读