使用https://www.gstatic.com/charts/loader.js

时间:2019-01-18 06:05:29

标签: javascript charts google-visualization

我有一个简单的代码,可以加载内容数组并绘制饼图。

<script type=text/javascript src=https://www.gstatic.com/charts/loader.js></script> 
<script type=text/javascript> 
      google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {

        var data = google.visualization.arrayToDataTable([
          ['Task', 'Hours per Day'],
          ['Work',     11],
          ['Eat',      2],
          ['Commute',  2],
          ['Watch TV', 2],
          ['Sleep',    7]
        ],false);

        var options = {
          title: 'My Daily Activities'
        };

        var chart = new google.visualization.PieChart(document.getElementById('piechart'));

        chart.draw(data, options);
      }
    </script>

<div id="piechart" style="width: 900px; height: 500px;"></div>

我想从txt文件读取数据表,其内容如下:

Task,Hours Per Day
Work,11
Eat,2
Sleep,7

有什么方法可以直接在上面的代码中加载txt文件?该文件可能还会不断更改。

1 个答案:

答案 0 :(得分:1)

您可以使用jquery获取文本文件并转换为数组。
您需要包含两个jquery文件,jquery本身和jquery csv,
以及Google图表库。

请参阅以下代码段...

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script> 
<script> 
  google.charts.load('current', {
    packages: ['corechart']
  }).then(function () {
    var options = {
      title: 'My Daily Activities',
      height: 500,
      width: 900
    };

    var chart = new google.visualization.PieChart(document.getElementById('piechart'));

    // get text file
    $.get('pie.txt', function(txt) {
      // convert csv to an array
      var arrayData = $.csv.toArrays(txt, {onParseValue: $.csv.hooks.castToScalar});

      var data = google.visualization.arrayToDataTable(arrayData);
      chart.draw(data, options);
    });
  });
</script>

<div id="piechart"></div>