开发者

Problems exporting to XLS with PHP + Jquery

I'm trying to export some tables generated with PHP from MySQL data. I'm trying to send the info via AJAX to a file with this code:

<?php
header("Content-type: application/vnd.ms-excel; name='excel'");  
header("Content-Disposition: filename=excel.xls");  
header("Pragma: no-cache");  
header("Expires: 0");  
echo $_POST['table'];
?>

The data comes from this function

function export_excel (id_table) {
    var table =  $("#" + id_table).html();
    $.ajax({
            t开发者_如何学Cype: 'POST',
            url: 'toexcel.php',
            data: 'table='+table
        });
}

Through Firebug I can see that the table is echoed correctly but it doesn't start any download. Which could be the problem?


It is not possible to start a file download as a response to an Ajax request. You have to send the browser to fetch the resource like if you were navigating to a page.

If you need to use the POST method, I think the ideal way to do this would be:

  • Have a real <form> element into which you write the POST data

  • Have an invisible or small iframe. Give it a name

  • Give the form the iframe name as the target property

  • submit() the form

if all headers are set correctly (You may have to add some more, like Content-disposition: attachment), this should trigger a file download without affecting your current page.

If you can use GET, a simple

location.href="toexcel.php?param1=value1&param2=value2"

should do already.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜