我在这个网站或其他网站(Redirect with POST to application/csv without form,jQuery.post(), PHP and redirects,.)读过很多文章。但没有任何有价值的解决方案。我的问题是:
var url= jmcnet.request.getOrigin()+'/commons/php/dt_csv_export.php' ; location.href = url+"?action=generate&csv_type=export_task&csv_data=" +encodeURIComponent(csv);
2.3 php脚本格式化输入(csv_data参数),编写一个临时文件并返回临时文件的内容。守则如下:
$h = @fopen($csv_file_name, 'w');
fputcsv($h, $csv_row, ',', '"');
fclose($h);
// export file content to JS
header('Content-Encoding: UTF-8');
header('Content-Type: text/ csv; charset =UTF-8');
header('Content-Disposition: attachment; filename=export-table.csv');
header(' Pragma: no-cache');
echo "\xEF\xBB\xBF"; // UTF-8 BOM
readfile($csv_file_name);2.4 php文件删除(取消链接)临时文件并退出,
我的问题是,当表很长时,调用的URL无效,对Php的JS调用被关闭。
因此,我设想以下3种解决方案,但没有明显的解决办法,所有这些都会导致其他问题:
我肯定我不是第一个遇到这个问题的人,所以我需要你的帮助,看看这个问题的最佳实践是什么。
发布于 2014-01-08 14:38:18
我觉得你把事情搞得有点复杂了。不需要所有JS重定向的东西,您只需将表单操作属性指向csv_export php代码,并使用POST发送数据。
如果需要,可以通过在post_max_size中编辑php.ini选项来修改post请求的最大大小。下面是我的照片:
; Maximum size of POST data that PHP will accept.
; Its value may be 0 to disable the limit. It is ignored if POST data reading
; is disabled through enable_post_data_reading.
; http://php.net/post-max-size
post_max_size = 8M至于写入临时文件,php已经在I/O流中构建了来处理这个问题。出于您的目的,您可能希望使用php://memory或php://temp (更多关于这些信息的信息:http://www.php.net/manual/en/wrappers.php.php)
所以你可以这样做:
示例HTML:
<html>
<head>
<!-- include jquery because you say you are using it -->
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
//just a dummy function to represent your js to extract csv data from a table
function extract_table_data(){
var csv = "field1,field2,field3\n\
value1,value2,value3\n\
value4,value5,value5";
return csv;
}
$( document ).ready(function() {
//export link click handler
$('#export_link').click(function() {
$('#csv_data').val(extract_table_data());
$('#theform').submit();
});
});
</script>
</head>
<body>
<a id='export_link'>Export CSV</a>
<form id='theform' method='post' action='dropcsv.php'>
<input type='hidden' name='csv_data' id='csv_data'/>
</form>
</body>
</html>dropcsv.php
//filename for our csv attachment
$export_filename = 'thefile.csv';
//grab csv data
$csv_data = $_POST['csv_data'];
//open file in memory
$f = fopen('php://memory', 'w'); //use php://temp if you want a tmp file instead
//load up csv file
fwrite($f, $csv_data);
// go back to the beginning of the file
fseek($f, 0);
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="'.$export_filename.'"');
fpassthru($f);
fclose($f);当然,不要忘记添加错误检查和清理输入。
https://stackoverflow.com/questions/20996750
复制相似问题