javascript - 使用 JQuery 通过 Ajax 请求时未下载文件

标签 javascript jquery ajax file csv

我需要从网站下载包含某些信息的 .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

引用此Force Download CSV File

简单地将超链接设置为

<a class="areaSummaryExport" href="admin_ajax.php" value="1">...</a>

关于javascript - 使用 JQuery 通过 Ajax 请求时未下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30921793/

相关文章:

javascript - 使用冒号、分号等符号将变量传递给 javascript 函数

javascript - 添加变量名称而不是其值,javascript

php - AJAX 自动刷新使得只有最后一个条目可见!

javascript - 拒绝加载字体 'data:font/woff.....' 它违反了以下内容安全策略指令 : "default-src ' self '". Note that ' font-src'

javascript - Src 更改在 Firefox 中有效,在 IE/Chrome 中无效

javascript - JS 类并覆盖 JQuery 事件处理程序

php - 从单独下载的 JPEG 创建电影时帧速率太慢

javascript - 与 JavaScript 中的原型(prototype)混淆

javascript - Redux 不会立即更新状态

php - ajax post 到 php 的撇号问题