用php和ajax生成并下载CSV文件 [英] Generate and download CSV file with php and ajax
问题描述
我有一个php
页面,该页面创建一个CSV文件,然后由浏览器自动下载.这是一个带有示例数据的版本-效果很好.
I have a php
page that creates a CSV file that is then downloaded by the browser automatically. Here is a version with sample data - it works great.
<?php
$cars = array(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=csvfile.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('Car', 'Year', 'Miles' ));
//Loop through the array and add to the csv
foreach ($cars as $row) {
fputcsv($output, $row);
}
?>
我希望能够使用ajax
从另一个页面运行此程序,以便用户无需离开主页即可生成/下载csv
.这是我在主页上使用的JavaScript
.在我的真实页面中,我使用的是通过ajax发送的数据.
I would like to be able to run this from another page using ajax
so that a user can generate/download a csv
without leaving the main page. This is the JavaScript
I am using on the main page. In my real page I am using the data coming via ajax.
$('button[name="exportCSVButton"]').on('click', function() {
console.log('click');
$.ajax({
url: 'exportCSV.php',
type: 'post',
dataType: 'html',
data: {
Year: $('input[name="exportYear"]').val()
},
success: function(data) {
var result = data
console.log(result);
}
});
});
当我单击按钮触发脚本时,它会运行,但是不会保存/下载到csv
,而是将整个内容打印到控制台.有什么办法可以实现我想要的吗?无需将文件实际保存到服务器并重新打开.
When I click the button to trigger the script, it runs, but instead of saving/download to csv
it prints the entire thing to console. Is there any way to accomplish what I want? Without actually saving the file to the server and reopening.
推荐答案
替换console.log(result);与文件保存代码. 在此处检查 JavaScript:创建并保存文件
Replace console.log(result); with file save code. check here JavaScript: Create and save file
使用浏览器对话框保存文件的最佳方法是使用简单的代码.
The best way to save file with browser dialog box, use simple code.
<a href="#" onclick="window.open('exportCSV.php?year=' + $('input[name="exportYear"]').val())" >Download File</a>
这篇关于用php和ajax生成并下载CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!