duanbeng1923 2015-01-13 17: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 17: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条)

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失