1 回答

TA貢獻(xiàn)1803條經(jīng)驗(yàn) 獲得超6個(gè)贊
你誤解了 XMLHttpRequest 的用途,它主要用于反應(yīng)性,例如當(dāng)我們想要加載由 php 生成的列表而無需重新加載頁面時(shí),
你可以用它來實(shí)現(xiàn)它,但因?yàn)槟悴恍枰?,一個(gè)簡單的方法是打開一個(gè) _blank 窗口到你提供的鏈接,這樣你的函數(shù)看起來像
function downloadGPXfile(fn) {
let script = `downloadGPXfile.php?filename=${fn}`;
window.open('http://website/downloadGPXfile.php?filename=' + fn, '_blank');
}
下載對(duì)話框顯示后,窗口關(guān)閉,因此您的 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);
echo "
<script>
window.close();
</script>";
?>
如果這對(duì)您不起作用,但為了清楚起見,窗口將顯示最多 1 秒然后關(guān)閉,您可以使用
function downloadGPXfile(fn) {
let fileurl = `http://website/downloadGPXfile.php?filename=${fn}`;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var downloadUrl = URL.createObjectURL(xhttp.response);
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = downloadUrl;
a.download = "";
a.click();
}
};
xhttp.open("GET", fileurl, true);
xhttp.responseType = "blob";
xhttp.send();
}
你看你需要刺激就像用戶點(diǎn)擊了一個(gè)有對(duì)象的
- 1 回答
- 0 關(guān)注
- 110 瀏覽
添加回答
舉報(bào)