首页  >  文章  >  web前端  >  如何在 PHP 中通过 AJAX 强制下载 CSV 文件?

如何在 PHP 中通过 AJAX 强制下载 CSV 文件?

Susan Sarandon
Susan Sarandon原创
2024-10-24 08:37:01224浏览

How to Force-Download a CSV File Through AJAX in PHP?

使用 PHP 和 AJAX 下载文件

问题:

如何通过 AJAX 强制下载 CSV 文件在 PHP 中调用?

背景:

您已经创建了一个 AJAX 函数,该函数根据用户输入生成 CSV 文件。创建后,您希望自动下载该文件而不提示用户。

PHP 代码:

在您的 PHP 文件 (csv.php) 中,您尝试了使用以下脚本强制下载 CSV 文件:

<code class="php">$fileName = 'file.csv';
$downloadFileName = 'newfile.csv';

if (file_exists($fileName)) {
    header('Content-Description: File Transfer');
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename='.$downloadFileName);
    ob_clean();
    flush();
    readfile($fileName);
    exit;
}
echo "done";</code>

问题:

当您在 csv.php 末尾运行此脚本时,以下内容

解决方案:

AJAX 无法直接下载文件。要强制下载文件,您可以使用以下方法之一:

  • 弹出新窗口:创建一个新窗口,并将下载链接作为其地址。
  • document.location = ...: 使用 document.location = ... 属性将文档的当前位置设置为下载链接。

示例:

您可以按如下方式修改 AJAX 函数,以弹出一个包含下载链接的新窗口:

<code class="javascript">function csv() {

    ajaxRequest = ajax();

    postdata = "data=" + document.getElementById("id").value;

    ajaxRequest.onreadystatechange = function () {
        var ajaxDisplay = document.getElementById('ajaxDiv');
        if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
            window.open(ajaxRequest.responseText);  // Pop up a new window with the download link
        }
    }

    ajaxRequest.open("POST", "csv.php", false);
    ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    ajaxRequest.send(postdata);
}</code>

以上是如何在 PHP 中通过 AJAX 强制下载 CSV 文件?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn