【问题标题】:On click file download, on success redirect to another page using AJAX单击文件下载,成功时使用 AJAX 重定向到另一个页面
【发布时间】:2015-01-13 17:19:22
【问题描述】:

在我的 WordPress 项目中,我的 Download 按钮包含一个 .zip 文件,应该下载该文件。所以生成的 HTML 是:

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

我正在使用 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>

在我添加带有链接的文件之前,一切正常。通常,此类链接将开始下载 .zip 文件,但即使在 AJAX 调用所花费的时间之后,页面也会重定向到下载成功页面,而不会触发下载。

而且大部分时间都会发生,只有一两次文件开始下载。

P.S.:我测试了this,但这不是我的情况。

【问题讨论】:

  • 不要这样做。通过 php 脚本提供文件,并在那里进行下载计数更新。这会更加可靠:脚本将捕获文件上的 ALL 命中,而不仅仅是“礼貌地”通过您的 html/js 的那些。

标签: javascript php jquery ajax wordpress


【解决方案1】:

同意@marc。只是为了添加更多信息,请执行此操作。

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

上面可以是下载的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);

试试这个,如果你有任何问题,请告诉我。

【讨论】:

  • 好的,考虑到你的建议,我可以成功重定向页面,顺便说一下文件下载是个废话。所以,我正在使用this 一堆代码,但在进入它之前,我尝试了:echo $file; if(file_exists($file)){ echo $file; },其中$file 显示github.com/nanodesigns/wp-adzonia/archive/v1.2.zip,但file_exists() 显示错误:@987654328 @
  • $_GET['file'] 必须防止不安全的输入!
【解决方案2】:

试试这个,

将带你到另一个页面

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

将带您到新窗口中的另一个页面

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

【讨论】:

    猜你喜欢
    • 2017-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-15
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    相关资源
    最近更新 更多