简体   繁体   English

JavaScript:如何下载文件,然后强制重新加载页面?

[英]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: 正如标题所提到的,我正在尝试通过href URL给出的PHP脚本下载一个与关联的mime类型一起提供的文件,然后重新加载同一页面,但是无法弄明白,这是我到目前为止所拥有的:

<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. 使用此代码,它将重新加载页面,但似乎不会调用PHP脚本。

As mentioned in the comments, I was able to get around the issue by adding a target="_new" attribute to the link. 正如评论中所提到的,我能够通过向链接添加target="_new"属性来解决此问题。 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. 因此,当单击链接时,它会将请求发送到远程php脚本到另一个窗口,该窗口将控制标头并开始下载文件,原始窗口将根据需要重新加载。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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