Download a file built in PHP output buffer from AJAX call

偶尔善良 提交于 2019-12-03 07:49:14

You can do this by creating and sending form via jquery (page not reloaded):

$(document).on('click', '#download', function () {
    var form = $(document.createElement('form'));
    form.attr('action', 'php.php');
    form.attr('method', 'GET');
    form.appendTo(document.body);
    form.submit();
    form.remove();
});

Also you can pass post parameters if need:

$(document).on('click', '#download', function () {
    var form = $(document.createElement('form'));
    form.attr('action', 'php.php');
    form.attr('method', 'POST');
    var input = $('<input>').attr('type', 'hidden').attr('name', 'x').val('x value');
    form.append(input);
    form.appendTo(document.body);
    form.submit();
    form.remove();
});

The following works, but is highly inneficient as it calls the php.php file twice. Does anybody have any better ideas?

<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <script type="text/javascript" language="javascript" src="jquery.js"></script>
        <script type="text/javascript">
             $("#download").live("click", function() {
                var request = $.ajax({
                    dataType: 'html',
                    url: 'php.php',
                    success: function(response) {
                        window.open('php.php');
                    }
                })
            })
        </script>
    </head>
    <body>
        <h1 id="download">DOWNLOAD</h1>
    </body>
</html>

Is there anyway to cache 'php.php' for just this instance so that it loads instantly under window.open('php.php'), but will reload contents when I click download next?

Why does window.open(response) not work the same?

look this:

if (!headers_sent()) {
    // seconds, minutes, hours, days
    $expires = 60*60*24*14;
    header('Pragma: public');
    header('Cache-Control: maxage=' . $expires);
    header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $expires) . ' GMT');
}

Note: this will not work with POST requests, just GET.

To allow for a file download, you can simply call the below code (say on a button's onclick):

window.open(<file-url>);

Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!