在一个PHP程序中,我输出了一段JavaScript代码,但它没有执行

前端开发 2026-07-08

这是程序的末尾。它会下载PDF文件或ePUB文件中的任意一种。
这部分工作非常顺利。但警报没有弹出,重定向也没有发生。哪里出了问题?

代码:

<?php    
if ($type == 'pdf')    
{   
    header('Content-type: application/pdf');    
    header('Content-Disposition: inline;filename="' . $fichier . '"');    
    header('Content-Transfer-Encoding: binary');    
    header('Content-Length: ' . filesize($file));    
    header('Accept-Ranges: bytes');    
    readfile($fichier); 
}   
else    
{   
    header('Content-Description: File Transfer');    
    header('Content-type: application/epub+zip');    
    header('Content-Disposition: attachment; filename="' . $fichier . '"');
    header('Content-Transfer-Encoding: binary');    
    header('Content-Length: ' . filesize($file));
    header('Accept-Ranges: bytes');   
    readfile($fichier);    
}
    echo "<script>alert('Votre fichier a été téléchargé.');</script>";
    echo "<script>window.location.replace('https://www.some_site/revue/ancetre');</script>";
?>
</body>
</html>

解决方案

你的代码要么向浏览器发送一个PDF,要么发送一个ePUB,浏览器会将其按相应的类型解释。

另一方面,像这样的HTML代码:

<script>alert('Votre fichier a été téléchargé.');</script>
<script>window.location.replace('https://www.some_site/revue/ancetre');</script>

应该是HTML页面的一个组成部分,浏览器会把它渲染成HTML。可是你并没有发送HTML页面。

换句话说:你发给浏览器的输出要么是PDF,要么是ePUB,要么是HTML页面,不能同时是这几种类型中的两种。页面的类型由内容类型头决定。对于HTML页面,在PHP中这是默认的。

Content-type: text/html; charset=utf-8

当你使用 header() 函数把它覆盖成 application/pdfapplication/epub+zip 时,它就不再是一个 text/html 页,也不再将该页解释为包含JavaScript的 HTML。参见: header()

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章