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条)

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型