繁体   English   中英

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

[英]File is not being downloaded when requested through Ajax using JQuery

我需要从网站上下载包含某些信息的.CSV文件,因此我正在使用链接和一些Javascript / JQuery从servr获取表并创建文件。

我具有应该在单击时下载文件的链接:
<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触发click事件,但是它也不起作用。

我建议您在服务器端PHP程序中创建CSV,并将Content-Type设置为“ application / vnd.ms-excel”(或)“ text / csv”,然后设置“ Content-Disposition:附件; [您的文件名]”

参考此为PHP中的用户创建CSV文件

请参考此强制下载CSV文件

只需将超链接作为

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM