我试图为用户开发一种通过jQuery / PHP下载CSV格式表的方法。
我有90%的工作,最后一点是我需要使用jQuery在用户浏览器中强制进行CSV下载。
我的PHP脚本
<?php
class Export {
public static function tocsv($results = array(), $fields = array(), $filename) {
$fh = fopen('php://output', 'w');
ob_start();
fputcsv($fh, $fields);
if(!empty($results)) {
foreach($results as $row) {
fputcsv($fh, (array) $row);
}
}
$string = ob_get_clean();
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=$filename");
exit($string);
}
}
?>
我的jQuery脚本
$(function() {
var btnName;
$('.button').click(function() {
btnName = $(this).attr('name');
btnValue = $(this).attr('value');
});
$("#spendReports").submit(function(event) {
event.preventDefault();
var formData = $('#spendReports').serializeArray();
formData.push({ name: btnName, value: btnValue });
$.post('spendReports.php', formData, function(data)
{
var data = $.parseJSON(data);
$.each(data, function(i, val) {
var newRow = '<tr><td class="dates-col" data-th="Date">' + data[i]["dates"] + '</td><td data-th="Project name">' + data[i]["project"] + '</td><td data-th="Total budget">' + data[i]["budget"] + '</td><td data-th="Plot numbers">' + data[i]["plots"] + '</td><td data-th="Categories">' + data[i]["categories"] + '</td><td data-th="Day work spent">£' + data[i]["day_work_spent"] + '</td><td data-th="% spend">' + data[i]["day_work_spent_percent"] + '%</td><td data-th="Price work spent">£' + data[i]["price_work_spent"] + '</td><td data-th="% spend">' + data[i]["price_work_spent_percent"] + '%</td><td data-th="Agency work spent">' + data[i]["agency_work_spent"] + '</td><td data-th="% spend">' + data[i]["agency_work_spent_percent"] + '%</td><td data-th="Subcon spent">' + data[i]["subcon_work_spent"] + '</td><td data-th="% spend">' + data[i]["subcon_work_spent_percent"] + '%</td><td data-th="Supervision spent">' + data[i]["supervision_spent"] + '</td><td data-th="% spend">' + data[i]["supervision_work_spent_percent"] + '%</td><td data-th="Total spent">£' + data[i]["total_spent"] + '</td></tr>';
$("#results > tbody").append(newRow);
});
});
});
});
这与Download File Using jQuery不同,因为我没有在服务器上物理创建文件,因此没有发送到jQuery的phsical链接。
答案 0 :(得分:0)
看一下这个答案:https://stackoverflow.com/a/4551467/563802
在你的情况下它应该是这样的:
var uriContent = "data:text/csv," + encodeURIComponent(data);
newWindow=window.open(uriContent, 'newDocument');