我在服务器上有一个简单的PHP脚本,目的是要下载指定的文件。如果我直接使用http://myDomain/download.php?filename=mini.gpx调用它,一切都工作正常。
download.php:
<?php
$dir = 'download/';
$file = $_GET['filename'];
$fqn = $dir . $file;
$fileSize = filesize($fqn);
header("Content-Type: text/xml");
header("Content-Disposition: attachment; filename=\"$file\"");
header("Content-Length: $fileSize");
readfile($fqn);
?>
但我希望从JavaScript启动这个脚本。因此,我尝试使用httpRequest来实现:
function downloadGPXfile(fn) {
let script = `downloadGPXfile.php?filename=${fn}`;
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
console.log("state downloadGPXfile: ", this.readyState);
console.log("status: ", this.status);
};
xhr.open('GET', script, true);
xhr.setRequestHeader('Content-Type', 'text/xml');
xhr.send();
}
虽然AJAX连接似乎成功了,但下载对话框没有被激活。我做错了什么?或者有另一个更简单的解决方案来启动下载吗?