简体   繁体   English

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

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

I need to download a .CSV file with certain information from a website, so I'm using a link and some Javascript/JQuery to get the table from the servr and create the file. 我需要从网站上下载包含某些信息的.CSV文件,因此我正在使用链接和一些Javascript / JQuery从servr获取表并创建文件。

I have this link that is supposed to download the file when clicked: 我具有应该在单击时下载文件的链接:
<a class="areaSummaryExport" value="1">...</a>

And then I have this in a JS file: 然后在JS文件中输入:

This adds the click listener to the link: 这会将点击侦听器添加到链接:

$('.areaSummaryExport').on('click', function(){
    exportAreaSummary($(this).attr('value'), $(this));
});

This function gets the table from the server using an ajax request and sends it to the corresponding function to process: 此函数使用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);
    });
}

Finally this function adds the href attribute to the link with the information of the file to download: 最后,此函数将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');
}

The problem is that it gets the info for the CSV file and adds it in the href attribute in the link, but it won't download the file (I have to click again for it to work). 问题在于,它获取CSV文件的信息并将其添加到链接的href属性中,但不会下载该文件(我必须再次单击才能使其工作)。

I know the last function works because I use it somewhere else, but there I already have the table on the screen so there's no ajax involved. 我知道最后一个函数有效,因为我在其他地方使用了它,但是在那里我已经在屏幕上找到表格,因此不涉及ajax。 So I'm guessing the problem is with the ajax, but not sure where. 所以我猜测问题出在ajax,但不确定在哪里。

I also tried firing the click event through JS but it doesn't work either. 我也尝试通过JS触发click事件,但是它也不起作用。

I would recommend you create the CSV at server side PHP program and set Content-Type as "application/vnd.ms-excel" (or) "text/csv" and set "Content-Disposition: attachment; [yourfilename] " 我建议您在服务器端PHP程序中创建CSV,并将Content-Type设置为“ application / vnd.ms-excel”(或)“ text / csv”,然后设置“ Content-Disposition:附件; [您的文件名]”

Refer this Create a CSV File for a user in PHP 参考此为PHP中的用户创建CSV文件

Refer this Force Download CSV File 请参考此强制下载CSV文件

Simply put hyperlink as 只需将超链接作为

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

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

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