我读过(在本网站或其他网站的文章很多不形重定向,以便用POST应用/ CSV,jQuery.post(),PHP和重定向,...),但没有任何有价值的解决方案。我的问题如下:
此功能实现如下:
2.1调用一个javascript来提取表的数据,
2.2此JS重定向到php服务,并将数据作为参数传递。代码如下:
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参数),编写一个temporay文件并返回临时文件的内容。代码如下:
$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调用已关闭。
因此,我想象以下三种解决方案,但是没有一个是显而易见的,并且都导致其他问题:
我确定我不是第一个遇到此问题的人,所以我需要您的帮助,以了解解决此问题的最佳方法。
我认为您可能会使这个问题变得过于复杂。不需要所有的JS重定向内容,您只需将表格action属性指向csv_export php代码并使用POST发送数据即可。
如果需要,您可以通过编辑php.ini中的post_max_size选项来修改发布请求的最大大小。这是我的样子:
; 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/zh-cn/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);
当然,不要忘记添加错误检查并清理输入。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句