我正在尝试使用jquery button onclick下载CSV文件。我有一个id为export
的<a>
标签,我希望它指向下载链接,在那里我可以下载我刚刚创建的CSV文件。
// Using this jquery to send my sql query to server-side-CSV
$('#export').on('click', function() {
var sqlsend = dataTable.ajax.json().sql;
$.post('server-side-CSV.php', 'val=' + sqlsend, function(request){
//code should go here
});
});
这里是我创建CSV文件的php代码
// This is my server-side-CSV file. It's creating a csv file to downloaded
<?php
require("connection.php");
$sql = $_POST['val'];
.
.more code
.
// loop over the rows, outputting them
while ($row = mysqli_fetch_assoc($rows)) fputcsv($output, $row);
fclose($output);
exit;
?>
如何下载CSV文件?
编辑:终于找到了答案,
$('#export').on('click', function() {
var sqlsend = dataTable.ajax.json().sql;
window.location.href="server-side-CSV.php?val="+sqlsend;
});
不发送$.post
,发送浏览器到下载位置:
document.location.href = 'server-side-CSV.php?val='+sqlsend;
你需要在循环前添加标题。
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");