duanbeng1923 2015-01-13 09:19
浏览 120
已采纳

在单击文件下载时,成功重定向到使用AJAX的另一个页面

In my WordPress project, my <kbd>Download</kbd> button containing a .zip file, which onClick should be downloaded. So the HTML producing is:

<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.

<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.

And it occurs most of the time, only once or twice the file starts downloading.

P.S.: I tested this but it's not my case.

  • 写回答

2条回答 默认 最新

  • duanji9311 2015-01-13 09:36
    关注

    Agree with @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

    //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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部