我有一个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
它将整个内容打印到控制台。有什么办法可以实现我想要的吗?无需实际将文件保存到服务器并重新打开。