我需要从网站下载包含某些信息的 .CSV 文件,因此我使用链接和一些 Javascript/JQuery 从服务器获取表并创建文件。
我有一个链接,单击该链接应该下载该文件:
<a class="areaSummaryExport" value="1">...</a>
然后我将其放入 JS 文件中:
这会将点击监听器添加到链接中:
$('.areaSummaryExport').on('click', function(){
exportAreaSummary($(this).attr('value'), $(this));
});
该函数使用ajax请求从服务器获取表格,并将其发送到相应的函数进行处理:
function exportAreaSummary(selected, sender){
$.ajax({
url: 'admin_ajax.php',
method: 'get',
dataType: 'json',
data: {action: 'exportAreaSummary', area: selected}
}).done(function(data){
console.log('done');
exportTableToCSV.apply(sender, [$($(data.table)[0]), data.name, data.header]);
}).error(function(XMLHttpRequest){
console.log('error');
console.log(XMLHttpRequest);
});
}
最后这个函数添加了 href
属性包含要下载的文件信息的链接:
function exportTableToCSV($table, filename, header) {
console.log('printing');
var $rows = $table.find('tr:has(td),tr:has(th)'),
// Temporary delimiter characters unlikely to be typed by keyboard
// This is to avoid accidentally splitting the actual contents
tmpColDelim = String.fromCharCode(11), // vertical tab character
tmpRowDelim = String.fromCharCode(0), // null character
// actual delimiter characters for CSV format
colDelim = '","',
rowDelim = '"\r\n"',
// Grab text from table into CSV formatted string
csv = '"' + 'sep=,' + rowDelim +
(header? header.join(colDelim) + rowDelim : '') +
$rows.map(function (i, row) {
var $row = $(row),
$cols = $row.find('td, th');
return $cols.map(function (j, col) {
var $col = $(col),
text = $col.text();
return text.replace(/"/g, '""'); // escape double quotes
}).get().join(tmpColDelim);
}).get().join(tmpRowDelim)
.split(tmpRowDelim).join(rowDelim)
.split(tmpColDelim).join(colDelim) + '"',
// Data URI
csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);
$(this)
.attr({
'download': filename,
'href': csvData,
'target': '_blank'
});
console.log('printed');
}
问题是它获取 CSV 文件的信息并将其添加到 href
中链接中的属性,但它不会下载该文件(我必须再次单击才能使其工作)。
我知道最后一个函数可以工作,因为我在其他地方使用它,但是屏幕上已经有了表格,所以不涉及ajax。所以我猜测问题出在ajax上,但不确定出在哪里。
我也尝试通过 JS 触发点击事件,但它也不起作用。
最佳答案
我建议您在服务器端 PHP 程序中创建 CSV,并将 Content-Type 设置为“application/vnd.ms-excel”(或)“text/csv”并设置“Content-Disposition:attachment; [yourfilename] ”
引用此Create a CSV File for a user in PHP
简单地将超链接设置为
<a class="areaSummaryExport" href="admin_ajax.php" value="1">...</a>
关于javascript - 使用 JQuery 通过 Ajax 请求时未下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30921793/