简体   繁体   English

点击文件下载后,成功使用AJAX重定向到另一个页面

[英]On click file download, on success redirect to another page using AJAX

In my WordPress project, my Download button containing a .zip file, which onClick should be downloaded. 在我的WordPress项目中,我的“ 下载”按钮包含一个.zip文件,应下载onClick。 So the HTML producing is: 因此,HTML产生为:

<a id="732" class="btn btn-default download-link" href="https://example.com/download.zip">DOWNLOAD</a>

I'm using AJAX to refresh the download count. 我正在使用AJAX刷新下载计数。

<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
jQuery(document).on('click', '.download-link', function () {
    var id = this.id;

    jQuery.ajax({
        type: 'POST',
        url: ajaxurl,
        data: {"action": "count_download",
                    "id": id
                },
        success: function (data) {
            window.location = site.url + "/download-success?fid="+ id;
        }
    });
});
</script>

Everything works fine until I added the file with the link. 一切正常,直到我添加了带有链接的文件。 Typically such a link will start downloading the .zip file, but even after the time taken by the AJAX call the page redirected to the download-success page without triggering the download. 通常,这样的链接将开始下载.zip文件,但是即使在AJAX调用花费的时间之后,该页面仍会重定向到下载成功页面,而不会触发下载。

And it occurs most of the time, only once or twice the file starts downloading. 而且它通常发生在大多数时间,只有一次或两次文件开始下载。

PS: I tested this but it's not my case. PS:我测试这个 ,但它不是我的情况。

Try this, 尝试这个,

Will take you to another page 将带您到另一个页面

success: function (data) {
    window.location.href = site.url + "/download-success?fid="+ id;
}

Will take you to another page in the new window 将带您到新窗口中的另一个页面

success: function (data) {
    window.open('site.url + "/download-success?fid="+ id');
}

Agree with @marc. 同意@marc。 Just to add more information, do this. 只是要添加更多信息,请执行此操作。

<a href='download.php?file=some_file.zip'>Download</a>

Above can be url link to download and below will be php code in download.php 上面可以是要下载的url链接,下面是download.php中的php代码

//code to update download count (UPDATE tbl_dwn SET total = total + 1)
//below is code to download (hope you know it)
$zipName = $_GET['file']; //here you've to specify the absolute path to the download.zip file
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=".$zipName."");
header("Content-length: " . filesize($zipName));
header("Pragma: no-cache"); 
header("Expires: 0");
readfile($zipName);

Try out this and let me know if you've any problem. 试试这个,让我知道您是否有任何问题。

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

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