您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使用“ AJAX”下载CSV文件

使用“ AJAX”下载CSV文件

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

基本方法

$('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,而是将副本保存在缓存中。我对此不太确定,但看起来很有希望。

其他 2022/1/1 18:20:28 有563人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶