通过 AJAX 调用时,PHP 下载脚本不起作用

我的服务器上有一个简单的 PHP 脚本,它应该下载给定的文件。如果我直接使用http://myDomain/download.php?filename=mini.gpx调用它,它工作正常


下载.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 连接似乎成功,但下载对话框并未激活。我做错了什么?还是有另一种更简单的解决方案来开始下载?


潇潇雨雨
浏览 59回答 1
1回答

慕码人8056858

你误解了 XMLHttpRequest 的用途,它主要用于反应性,例如当我们想要加载由 php 生成的列表而无需重新加载页面时,你可以用它来实现它,但因为你不需要它,一个简单的方法是打开一个 _blank 窗口到你提供的链接,这样你的函数看起来像function downloadGPXfile(fn) {&nbsp; &nbsp; let script = `downloadGPXfile.php?filename=${fn}`;window.open('http://website/downloadGPXfile.php?filename=' + fn, '_blank');}下载对话框显示后,窗口关闭,因此您的 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);&nbsp; &nbsp;echo "<script>window.close();</script>";?>如果这对您不起作用,但为了清楚起见,窗口将显示最多 1 秒然后关闭,您可以使用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) {&nbsp; &nbsp; var downloadUrl = URL.createObjectURL(xhttp.response);&nbsp; &nbsp; var a = document.createElement("a");&nbsp; &nbsp; document.body.appendChild(a);&nbsp; &nbsp; a.style = "display: none";&nbsp; &nbsp; a.href = downloadUrl;&nbsp; &nbsp; a.download = "";&nbsp; &nbsp; a.click();}};xhttp.open("GET", fileurl, true);xhttp.responseType = "blob";xhttp.send();}你看你需要刺激就像用户点击了一个有对象的
打开App,查看更多内容
随时随地看视频慕课网APP