Download a file by clicking a button

前端 未结 1 359
你的背包
你的背包 2021-01-28 19:08

This is the HTML:


I want users to download a file when they click this button. For that

相关标签:
1条回答
  • 2021-01-28 19:40

    Don't use AJAX to download a file. It's not that it can't make the request and receive the response, it's just that it doesn't really have any meaningful way to handle the response.

    The browser itself, on the other hand, does.

    So you can just direct the browser to the request:

    $parent.find('button[name=download]').click(function () {
        window.location.href = 'download.php';
    });
    

    If download.php is sending a response of Content-Disposition: attachment; then the page isn't going to be unloaded or modified in any way. The browser is going to handle the response of this request entirely separately from the current page context, and after handling the response that page context will remain.

    (Unless, of course, the browser is configured to do something with that response, such as always display it instead of prompting to save it. But there's nothing you can do about that in code.)

    At this point, in fact, it makes even more sense to just remove the JavaScript entirely and make it a normal link, which would accomplish the same thing:

    <a href="download.php">Download</a>
    

    You can style it to look like a button, which it probably more accessible than an actual button running JavaScript code. (If the browser doesn't have JavaScript enabled then the button would be useless, but a link would work just fine.)

    0 讨论(0)
提交回复
热议问题