我自己找到了解决方案。而不是AJAX
使用Iframe
技术。以下jQuery
代码应写在 iframe 中。它通过 iframe 触发下载,而不是AJAX
向服务器发出请求。
$(document).ready(function(){
$('#download').click(function(){
var ifr = $('<iframe id="secretIFrame" src="" style="display:none; visibility:hidden;"></iframe>');
$('body').append(ifr);
var iframeURL = 'http://you_domain.com/download.php?str='+encodeURIComponent(data_to_be_posted);
ifr.attr('src', iframeURL);
return false;
});
});
这是代码download.php
:
<?php
$str = html_entity_decode($_REQUEST['str']);
$file_name = 'export_data.txt';
header("Cache-Control: ");// leave blank to avoid IE errors
header("Pragma: ");// leave blank to avoid IE errors
header("Content-Disposition: attachment; filename=\"".$file_name."\"");
header("Content-length:".(string)(filesize($str)));
header("Content-Type: application/force-download");
header("Content-Type: application/download");
header('Content-Type: application/octet-stream');
header('Content-Type: application/txt');
header("Content-Transfer-Encoding: binary ");
echo $str;
exit;
?>