Google Charts CSV下载按钮异常:浏览器无法找到下载文件
问题分析与修复方案
核心问题1:drawToolbar的数据源类型错误
Google Charts的drawToolbar组件要求datasource参数传入DataTable对象,而非你提前转换好的CSV字符串。当前你把csv_data(字符串类型)传给它,会直接导致导出功能无法生成有效文件。
核心问题2:JS语法错误阻断代码执行
饼图配置options里,fill: 'transparent'末尾缺少逗号,这会触发JavaScript语法错误,导致后续工具栏绘制的代码无法执行。
次要问题:参数传递缺失
调用create_piechart(res)时未传入class_choice参数,导致空数据提示中的class_choice显示为undefined,影响用户体验。
修复后的完整代码
function google_piechart() { var class_choice = $('#class_choice').val(); if (class_choice == null) { alert('Please select a class.'); return false; } console.log('Selected class:', class_choice); // get data from output of Python script $.get("https://bioed.bu.edu/cgi-bin/students_23/Team_H/class_cgi.py", {selector: 'piechart', class_choice:class_choice}, function (res){ console.log('Received data:', res); // 修复:传入class_choice参数 create_piechart(res, class_choice); }, "json" ); } // define that function here, now function create_piechart(res, class_choice) { console.log('Processed data:', res, class_choice); global_data1 = res if (res.length === 0) $('#piechart').html('There was no data for the class choice: ' + class_choice); let formatted_results = res.map(item => item.slice(0, 2)); console.log(formatted_results); // adding a header formatted_results.unshift(["Transposon Order", "Count"]); // get the total count of results let total_count = res.reduce((sum, item) => sum + item[1], 0); console.log('Total count:', total_count) // return total count to the screen for the user $('#result_count').html('Total number of results: ' + total_count); // loading Google charts info google.charts.load('current', {'packages': ['corechart', 'table', 'gauge']}); google.charts.setOnLoadCallback(function () { // format processed data for use w/ Google charts var chart_data = google.visualization.arrayToDataTable(formatted_results); console.log('Chart data:', chart_data); // options for the piechart var options = { title: 'Transposon Orders by Class', fill: 'transparent', // 修复:添加逗号 is3D: true, colors: ['#0072B2', '#E69F00', '#009E73', '#F0E442', '#CC79A7', '#D55E00', '#56B4E9', '#0072B2', '#F0E442', '#009E73', '#D55E00', '#CC79A7'] }; // finally creating the pie chart var chart = new google.visualization.PieChart(document.getElementById('piechart')); chart.draw(chart_data, options); // create a table with the same data var table = new google.visualization.Table(document.getElementById('table1')); table.draw(chart_data, { title: 'Transposon Orders by Class', showRowNumber: false, width: '50%' }); // 修复:直接传入DataTable对象给工具栏组件 var components = [ {type: 'csv', datasource: chart_data} ]; var toolbarContainer = document.getElementById('toolbar_div1'); google.visualization.drawToolbar(toolbarContainer, components); }); }
验证步骤
- 打开浏览器开发者工具(F12),切换到Console标签,确认无语法错误。
- 检查HTML中是否存在
toolbar_div1元素,且ID拼写正确。 - 测试导出功能,此时应能正常生成并下载CSV文件。
内容的提问来源于stack exchange,提问作者thecatsmilk
相关产品推荐
相关产品推荐

