我有一个php
页面,它创建一个CSV文件,然后由浏览器自动下载。这里是一个带有示例数据的版本 - 它运行得很好。
<?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
获取的数据。$('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
文件,而是将整个内容都打印到了控制台上。有没有什么办法可以实现我想要的效果?而不必真正将文件保存在服务器上并重新打开。
window.location.assign('path_to_csv_generated_file')
,确保文件位于公共可访问目录中。完成后即可。 - Muhammad Omer Aslam