driuwt9557 2013-12-05 14:10
浏览 24
已采纳

将JavaScript ID值传递给PHP以供下载

I am pretty new to PHP but I am learning fast.. I have been trying to use AJAX to Pass An ID to PHP. With this ID I use SQL to get the path of a file from the database than use it to download the file. However after some research this is not possible and I couldn't understand alternives... maybe there is a workaround?

These are my JavaScript function; I used JSON because I was passing an Array of IDs because I intend to use it in future for multiple downloads. I get the IDs from a table row click.

$('.btnDownload').click(function() {
                $.ajax({
                    url: 'scripts/downloadFile.php',
                    type: "POST",
                    data: {id: JSON.stringify(fileID)}
                });
            });

And my PHP to attempt to download the file;

<?php
    $data = $_POST['id'];
    $data = json_decode("$data", true);
    $countArray = count($data);
    $counter = 0;
while($countArray > $counter){
        $getID = $data[$counter];
// My sql connections and queries, jumped to the fetch part
$filePath = $fetch['filePath'];
                    header('Content-Type: application/zip');
                    header('Content-Disposition: attachment; filename='.basename($filePath));

                    readfile($filePath);
                    exit;
$counter++; 
    }
?>

How ever this script alone works when I give a static path and run it with my browser. I would like some help on alternatives on achieving the results.

  • 写回答

3条回答 默认 最新

  • doutan1875 2013-12-05 15:41
    关注

    To solve the problem relating to the popup not popping up, try something like this instead of ajax:

    $('.btnDownload').click(function(event) {
        var url = 'scripts/downloadFile.php?id=' + JSON.stringify(fileID);
        window.location.href = url;
        event.preventDefault();
    })
    

    The user should be presented with a "save file" dialog and the browser will remain on the same url due to the disposition headers set by the php file.

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

报告相同问题?

悬赏问题

  • ¥15 爬取1-112页所有帖子的标题但是12页后要登录后才能 我使用selenium模拟登录 账号密码输入后 会报错 不知道怎么弄了
  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点