简体   繁体   English

JQuery 和 PHP:是否可以通过 AJAX 调用下载文件?

[英]JQuery and PHP: is it possible to download a file via an AJAX call?

I've got a web page that displays data in a table and what I want to add is a button that the user can click to download the table as an Excel file.我有一个 web 页面,它在表格中显示数据,我想添加一个按钮,用户可以单击该按钮将表格下载为 Excel 文件。 I use PHPExcel to make the Excel file, and it seems to work with no errors until I actually get to downloading the file - it seems the browser generates the file just fine, but doesn't actually download the finished file.我使用 PHPExcel 制作 Excel 文件,在我真正下载文件之前它似乎没有错误 - 浏览器似乎生成文件很好,但实际上并没有下载完成的文件。

I did take a look at this question here: phpexcel to download , but I tried what the answers said to do and it didn't seem to change anything.我确实在这里查看了这个问题: phpexcel to download ,但我尝试了答案所说的,它似乎没有改变任何东西。

Here's my frontend code ("table.php"):这是我的前端代码(“table.php”):

<script>
$("#export-to-excel").click(function() {
            $.ajax({
                type: "GET",
                url: "table_create_excel.php",
                data: {
                    action: "exportToExcel",
                    tableRows: rows
                }
            });
}
</script>
<img src='excel-icon.png' id="export-to-excel"/>

Here's my backend code ("table_create_excel.php"):这是我的后端代码(“table_create_excel.php”):

    require_once "PHPExcel.php";
    $objPHPExcel = new PHPExcel();
    // ...
    // ... generate the excel document from the given data ...
    // ...
    $objPHPExcel->setActiveSheetIndex(0);
    
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="Table_Summary.xlsx"');
    header('Cache-Control: max-age=0');

    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    $objWriter->save('php://output');

Is there something I'm missing that, if I could put it in, would get my browser to download the file?有什么我遗漏的东西,如果我能把它放进去,会让我的浏览器下载文件吗? Could the trouble be because I'm making an AJAX call rather than linking to the PHP page directly?问题可能是因为我正在进行 AJAX 调用而不是直接链接到 PHP 页面吗? Thanks.谢谢。

Turns out my suspicion was correct, and that you can't use AJAX to download a file.原来我的怀疑是正确的,你不能使用 AJAX 下载文件。 What I did was got rid of the JQuery "click" event and replaced it with an anchor tag around the "export to Excel" icon, which had a link to the PHP file that generated and downloaded the Excel file along with enough parameters to allow the PHP code to re-query the database and rebuild the table that I wanted to export rather than including the table in the data that was sent.我所做的是摆脱了 JQuery “点击”事件,并将其替换为“导出到 Excel”图标周围的锚标记,该标记具有指向 PHP 文件的链接,该文件生成并下载了 ZC1D81AF5835844B4E9D936910 文件,以允许使用足够的参数来下载 ZC1D81AF5835844B4E9D936910 文件PHP 代码重新查询数据库并重建我想要导出的表,而不是将表包含在发送的数据中。

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

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