使用“ AJAX”下载CSV文件

我正在尝试为我的网站完成一个相当简单的任务,但是我不确定该如何去做。我希望用户查看表格,然后单击一个按钮,此时用户可以保存该表的内容作为csv文件。此请求有时可能非常复杂,因此我生成了一个进度页来提醒用户。

除了实际生成csv文件之外,我已经弄清了大多数东西。(我使用jQuery和PHP)

jQuery代码在单击时运行:

hmis_query_csv_export: function(query_name) {

$.uiLock('<p>Query Loading.</p><img src="/images/loading.gif" />')

$.get({

url: '/php_scripts/utils/csv_export.php',

data: {query_name: query_name},

success: function(data) {

$.uiUnlock();

}

});}

相关的PHP:

header("Content-type: text/x-csv");

header("Content-Disposition: attachment; filename=search_results.csv");

//

//Generate csv

//

echo $csvOutput

exit();

这样做是将文本作为PHP文件发送,但不会生成下载。我究竟做错了什么?

回答:

如果要强制下载,则可以将当前页面重定向到下载链接。由于链接将生成一个下载对话框,因此当前页面(及其状态)将保留在原位。

基本方法:

$('a#query_name').click(function(){

$('#wait-animation').show();

document.location.href = '/php_scripts/utils/csv_export.php?query_name='+query_name;

$('#wait-animation').hide();

});

更复杂:

$('a#query_name').click(function(){

MyTimestamp = new Date().getTime(); // Meant to be global var

$('#wait-animation').show();

$.get('/php_scripts/utils/csv_export.php','timestamp='+MyTimestamp+'&query_name='query_name,function(){

document.location.href = '/php_scripts/utils/csv_export.php?timestamp='+MyTimestamp+'&query_name='+query_name;

$('#wait-animation').hide();

});

});

在PHP脚本中:

@header("Last-Modified: " . @gmdate("D, d M Y H:i:s",$_GET['timestamp']) . " GMT");

@header("Content-type: text/x-csv");

// If the file is NOT requested via AJAX, force-download

if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {

header("Content-Disposition: attachment; filename=search_results.csv");

}

//

//Generate csv

//

echo $csvOutput

exit();

两个请求的URL必须相同,以欺骗浏览器不要在处开始新的下载document.location.href,而是将副本保存在缓存中。我对此不太确定,但看起来很有希望。

以上是 使用“ AJAX”下载CSV文件 的全部内容, 来源链接: utcz.com/qa/415456.html

回到顶部