简体   繁体   中英

JavaScript: How to download a file, then force a page reload?

As the title mentions, I am trying to download a file which is served with associated mime type via PHP script given by href URL, then reload the same page, but can't quite figure it out, here's what I have so far:

<a id="viewAttachmentLink" href="/path/to/script.php?id=123">View Attachment</a>

<script type='text/javascript'>
    jquery('#viewAttachmentLink').bind('click', function() {
        if (myFunction()) {
            window.location.href = "jquery(this).attr('href')";
            setTimeout(location.reload(), 400);
        } else {
            return false;
        }
    });
</script>

With this code, it will reload the page, but appears to not make the call to the PHP script.

As mentioned in the comments, I was able to get around the issue by adding a target="_new" attribute to the link. So when the link was clicked it would send the request to the remote php script to another window, which would control the headers and start downloading the file, and the original window would reload as needed.

I did a file download and status update (through a header) like this:

<a id="downloadData">Download data...</a>

<script type="text/javascript">
    $('#downloadData').on('click', function () {
        $.ajax({
            url: '/data',
            method: 'GET',
            success: function (data, textStatus, request) {
                var output = request.getResponseHeader('output');
                //refresh page here and use the output
                //console.log(output);
                var a = document.createElement('a');
                var url = '/data';
                a.href = url;
                a.click();
                //save file
            },
            error: function (e) {
                console.log(e);
            }
        });
    });
</script>

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