gpt4 book ai didi

javascript - 加载图表后如何获取 Google Visualization DataTable 数据?

转载 作者:可可西里 更新时间:2023-11-01 01:54:18 25 4
gpt4 key购买 nike

我想从页面抓取 Google Chart 数据,将其转换为 CSV,然后将其交给下载程序。

在 chartpage.js 中

function downloadCSV(args) {
var csvData, filename, link;
var action = args.action_name;
var csv = convertArrayOfObjectsToCSV({
action_name: action
});
filename = args.filename || 'export.csv';

csvData = encodeURI(csv);

link = document.createElement('a');
link.setAttribute('href', 'data:text/csv;charset=utf-8,' + csvData);
link.setAttribute('type', 'data:text/csv;charset=utf-8');
link.setAttribute('download', filename);
link.click();
}

然后在 chart.coffee 中:

 init_chart = ->
chart = new google.visualization.BarChart(document.getElementById('chart_div')); //#chart_div in chart.html.haml

render_chart = (items, year)->
@data = new google.visualization.DataTable()
data.addColumn 'string', I18n.t('charts.name')

// Other logic for building chart from Rails DB Data

for key_item in items
label = []
[key, item] = key_item.split(':')

if key == 'competitor_meded_involvement'
label.push I18n.t('charts.competitor')

label.push I18n.t("kol_items.#{item}")

data.addColumn 'number', label.join(' - ')

// and so on.

google.charts.load 'current', 'packages': ['corechart']

google.visualization.events.addListener(@data, 'ready', setData) // I read this was a solution but it doesn't seem to help

google.charts.setOnLoadCallback ->

init_chart()

render_chart()

$(setData(@data)) //I tried passing this to a setter method over in chartpage.js which takes @data and tries to set it globally but that makes no difference at page load time.

在 chart.html.haml 中:

 %h5{id: "downloadCSV"}= link_to '<i class="fa fa-file-excel-o"></i> Download CSV'.html_safe, "#"

#chart_div

所以我在主 JS 中同时尝试以上和以下内容:

case 'chart_kol_comparison':
google.setOnLoadCallback(function() {
str = google.visualization.dataTableToCsv(window.data); //This builds the CSV string and returns it to the download JS for output
});

但是来自页面 JS (HAML) 的数据变量:

 @data = new google.visualization.DataTable()

似乎只有在页面加载后才可用——当上面的 JS 加载并试图获取数据时不可用。

当我在控制台中运行以下命令时有效,但在页面加载时无效。这是在 Rails 应用程序中。

 str = google.visualization.dataTableToCsv(data); //var data is populated after page loads (available from console) but not from the JS at page load time.

我该怎么做?

最佳答案

这里似乎发生的事情是您没有在调用 draw 后等待图表/数据表完全呈现。因此,实现此目的的最佳方法是创建一个事件处理程序,等待图表/数据表的就绪事件。

google.visualization.events.addListener(tableChart, 'ready', myReadyHandler);

然后添加填充变量的函数,但要在图表/数据表准备好之后。

function myReadyHandler(){
// fill variables here or call directly your other methods,
// this will ensure, you can grab data from the chart/datatable
// because is completely rendered and you can play with that
}

关于javascript - 加载图表后如何获取 Google Visualization DataTable 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50662402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com