Fetch函数在等待答案,但在PHP产生输出之前,结果就会不同

前端开发 2026-07-10

JavaScript调用PHP的例程:

async function genPdf() {
    try {
        const response = await fetch('genPdf.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
                }
        });
        const data = await response.text();
        console.log("Server answer:", data);
    } catch (error) {
        console.log("Server answer:", "error");
        }
    }

然后PHP例程对该请求作出回应:

<?php

....Built a PDF with FPDF....

then:

$pdf->Output('D', $urlPdf);  // to force browser to download pdf file.

then send the answer fetch function are waiting for:

$result = array("pdf" => "ok", "status" => true);
header('Content-Type: application/json');
echo json_encode($result);
?>

在这种模式下,首个输出($pdf->output),并不是强制下载,而是把PDF文件作为字符串发送给fetch函数,显然执行也不能正确继续。文件没有被下载,响应的JavaScript也没有正确到达。

我在寻找一种方法,能够下载由PHP例程生成的文件,并在继续之前收到任务已成功完成的响应。

解决方案

使用下面的代码

PHP(genPdf.php)

<?php
// ... generate your PDF ...
$filename = "report_" . time() . ".pdf";
$filepath = "temp/" . $filename;

// Save the file to your server instead of outputting it to the buffer
$pdf->Output($filepath, 'F'); 

$result = array(
    "status" => true, 
    "pdf_url" => "https://yourdomain.com/temp/" . $filename
);

header('Content-Type: application/json');
echo json_encode($result);
?>

JavaScript

const data = await response.json(); // Use .json() instead of .text()

if (data.status) {
    // Open the PDF in a new tab
    window.open(data.pdf_url, '_blank');
}
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章