使用带有 JS 输入的标头下载文件


Downloading files using Header with a JS input

我有一个页面,它有一个JavaScript函数,它使用Post将变量发送到php文件。问题是,我正在使用"header"来下载文件,而我的JS没有在新页面中打开PHP脚本。

当我在新页面中打开 php 文件时,它没有从 JS 接收到所需的变量。

我知道这听起来令人困惑,但我希望我的代码可以阐明我的问题。

简短的版本是,我正在尝试下载由单选按钮选择的文件。我使用 JS 检查选中了哪个单选按钮,然后将其发送到我的 php 文件。然后需要下载文件。

提前谢谢大家。

.PHP:

<?php
if (isset($_POST['routenumber'])) {
if(!isset($_SESSION)){session_start();}
$routenumber = (isset($_POST['routenumber']) ? $_POST['routenumber'] : null);

$directory = ("Users/".$_SESSION['id']."/SavedRoutes/");
$routes = scandir($directory);
sort($routes);
$route = $routes[$routenumber];
$file =("Users/".$_SESSION['id']."/SavedRoutes/".$route);

header("Content-type: application/gpx+xml");
// header("Content-Disposition: attachment;Filename=".json_encode($route).".gpx");
header("Content-Disposition: attachment;Filename=route.gpx");

readfile($file);
}
?>

.JS:

function fuAccountDownloadRoute(){
var i=2;
var SelectedRadio
while (i < routecounter){
    var str1='radio';
    var str2=JSON.stringify(i);
    var result = str1.concat(str2);
    if (document.getElementById(result).checked){
        SelectedRadio = result.slice(5);
    }
    i=i+1;  
}

$.post('accountPage.php',{routenumber:SelectedRadio});
}

> 当你在浏览器中打开 url: http://localhost/accountPage.php 时,它会发出 GET 请求。如果你想让它成为可能,你应该在你的代码中把所有的 $_POST 更改为 $_GET,然后你可以像这样打开它:http://localhost/accountPage.php?routenumber=3,尽管它可能不是你真正想要的。