使用 window.location.href 后无法在 iframe 中输出内容

3

我正在使用window.location.href在一个php函数中,该函数可以强制下载文件而不会打开其他窗口。文件下载成功并且php脚本的其余部分也执行了。然而,在函数中包含javascript代码的那一行之后输出的任何内容都不会显示在iframe中。有没有办法将输出重定向回原来的php脚本?

以下是php文件中的javascript代码:

echo "<script>window.location.href='download.php';</script>";

这里是download.php的代码:
<?php
session_start(); // Starts new or resumes existing session
$filename = $_SESSION['filename']; // Creates variable from session variable
header("Content-Type: text/plain"); // Output text file
header("Content-Disposition: attachment; filename=$filename"); // Output file name
readfile($filename); // Outputs the text file
?>

这是一个php文件中的示例,在javascript行后不会输出到iframe中。
echo 'Test Output';

提前致谢,

Jay

编辑

我用以下代码替换了javascript代码行,现在它完美地工作了:

echo "<iframe id='my_iframe' style='display:none;' src='download.php'></iframe>";

1
如果您重定向了页面,则它会显示新页面所显示的内容而不是旧页面。将您的回音放在下载文件PHP脚本中,它应该会显示。 - Moussa Khalil
谢谢您的回复。那很有道理。有没有办法重定向回已经运行的 PHP 文件? - jgc9876
1
不切实际。而且你也不会真正使用 iframe 进行下载,更像是一个页面。查看答案以获取更好的方法 :) - Moussa Khalil
1个回答

1

您不需要将重定向放在iframe页面内。

我目前想到的最好的方法是使用一个不可见的框架,就像Andrew Dunn在question中提到的那样。

引用他的答案:

<iframe id="my_iframe" style="display:none;"></iframe>
<script>
function Download(url) {
document.getElementById('my_iframe').src = url;
};
</script>

在您的主页面中添加此内容。url 基本上是下载 url(在您的情况下为 "download.php")。您可以使用按钮进行手动下载。如果想要强制下载,将 src=url 添加到 iframe 中并删除脚本。
我建议研究并使用 jQuery。

太棒了,我用以下代码替换了javascript行:echo "<iframe style='display:none;' src='download.php'></iframe>"; 现在脚本可以下载文件并按预期输出。感谢您的帮助。 - jgc9876

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接