【问题标题】:Javascript code does not execute while php redirectphp 重定向时 Javascript 代码不执行
【发布时间】:2021-06-07 11:42:49
【问题描述】:

我有两个 PHP 文件。

index.php 允许用户上传图片。上传的数据被发送到另一个页面,即 upload.php,在那里我检查某些条件,例如上传的图像是否真的是图像而不是其他文件,以及图像是否已经存在于服务器上等;

我希望看到我的 upload.php 页面在错误条件下重定向回 index.php 页面。我看过很多关于重定向的帖子,例如,通过使用标题,我就是这样做的。好吧,它确实重定向。但是,javascript 代码的某些部分无法执行。我想在我的 upload.php 页面上看到那个警告框,它在用户交互时重定向到 index.php。

提示框暂时没有出现,但是页面会重定向

我的问题可能很琐碎,但我是 PHP 新手。

index.php

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>

上传.php

$target_dir = "uploads/";
$file_name=basename($_FILES["fileToUpload"]["name"]);
$target_file = $target_dir . $file_name;
$uploadOk = 1;

if (file_exists($target_file)) {
    $uploadOk = 0;
    echo "<script language='javascript'>
            alert('Sorry, file already exists.Consider Renaming or upload new file');
            </script>";
    header("Location: http://xx.yyy.zz");
    exit;
}

【问题讨论】:

  • 您的要求毫无意义。重定向命令的全部意义在于它告诉浏览器忽略当前输出并转到新指定的 URL。在此过程中,您预计该警报何时出现?浏览器在读取标题时重定向,它不等待任何其他信息。如果你想显示当前脚本的结果,然后重定向,你必须使用 Javascript 的 window.location 命令进行 client-side 导航,该命令将在警报之后运行已关闭。
  • 但实际上,在重定向到的页面上简单地显示任何错误会更加用户友好,然后用户在解除警报后不必记住它们。您可以将错误消息放入会话中,或者在重定向 URL 中将错误代码作为查询字符串变量传递,以便接收页面从预先确定的列表中知道要显示的错误消息。
  • @ADyson 感谢您的宝贵反馈

标签: javascript php forms


【解决方案1】:

您可以将“HTTP 标头重定向”替换为在 javascript 中完成的重定向。

删除代码

header("Location: http://xx.yyy.zz");

并将 echo 命令替换为

echo "<script language='javascript'>
        alert('Sorry, file already exists.Consider Renaming or upload new file');
        window.location = "http://xx.yyy.zz";
        </script>";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-27
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多