简体   繁体   中英

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. 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.

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.

Here's my frontend code ("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"):

    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? Thanks.

Turns out my suspicion was correct, and that you can't use AJAX to download a file. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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