2016-11-14 82 views
1

我想下载一个使用jQuery按钮onclick CSV文件。我有一个<a>标记,其ID为export,我希望它指向下载链接,我可以下载我刚刚创建的CSV文件。jQuery下载一个csv文件与链接onclick

// 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 
    }); 
}); 

这是我的PHP代码在那里我创建一个CSV文件

// 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; 
}); 
+0

要么使用表单,要么打开弹出窗口,或者使用[数据URI](http://stackoverflow.com/questions/3665115/create-a-file-in-memory-for-user-to-下载不通过服务器) – nicovank

+0

如果我使用的URI,那么我将如何能够发送'sqlsend'变量到我的PHP文件?我很抱歉,对这一切都很新颖。 –

+0

你的'request'文件是否被下载? –

回答

0

代替$.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"); 

请参阅this answer

+0

是的,我已经拥有了所有这些标题。 Stackoverflow没有让我添加所有的代码。 –

+0

我建议检查你的server-side-CSV.php文件是否适用于一些硬编码的SQL。直接从浏览器调用它。 – olegsv

+0

是的,当我通过我自己的SQL查询时它工作得很好。当我通过sql查询,函数(请求)时,这个'请求'变量包含所有的数据,但没有显示任何下载弹出窗口。 –