PHP:给出警报弹出窗口然后重定向页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11703854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP: give alert popup then redirect the page
提问by Eric Kim
I am new to PHP.
我是 PHP 新手。
When someone uploads a file size too big, I want to show them a warning popup and redirect them to a previous page (or vice versa).
当有人上传的文件太大时,我想向他们显示警告弹出窗口并将他们重定向到上一页(反之亦然)。
if(file size is too big){
ob_start();
header("location:index.php");
echo "<script type='text/javascript'>alert('Your File Size is too big!');</script>";
ob_end_flush();
exit;
}
This code above will just redirect me to index.php and doesn't show any warning popup.
上面的这段代码只会将我重定向到 index.php 并且不显示任何警告弹出窗口。
回答by Basic
Do something like
做类似的事情
header("Location: index.php?Message=" . urlencode($Message));
Then on index.php...
然后在 index.php ...
if (isset($_GET['Message'])) {
print $_GET['Message'];
}
In other words, index.phpwill always check if it's being passed a message in the url. If there is one, display it. Then, just pass the message in the redirect
换句话说,index.php将始终检查它是否在 url 中传递了一条消息。如果有,就显示出来。然后,只需在重定向中传递消息
if you really want to use a modal popup, generate the js...
如果您真的想使用模态弹出窗口,请生成js ...
if (isset($_GET['Message'])) {
print '<script type="text/javascript">alert("' . $_GET['Message'] . '");</script>';
}
Note that this will break if you use quotes in the message unless you escape them
请注意,如果您在消息中使用引号,这将中断,除非您将它们转义
回答by Marco
<script type="text/javascript">
alert("YOUR MESSAGE HERE");
location="REDIRECTION_PAGE.php";
</script>
回答by Andrew Gorcester
The problem is that header("location:index.php");sets the response code to 302automatically. The browser immediately redirects without looking at the contents of the page.
问题是header("location:index.php");将响应代码设置为302自动。浏览器立即重定向而不查看页面内容。
You need to either do the redirect itself in javascript after the alert is sent, or else have the page you're redirecting to do the alert.
您需要在发送警报后在 javascript 中执行重定向,或者让您重定向的页面执行警报。
回答by Shashank Srivastava
The code goes like:
代码如下:
if($_FILES['file']['size'] > 200000) //any file size, 200 kb in this case
{
echo "<script type='javascript'>alert('File size larger than 200 KB')</script>";
}
header("Location: index.php");
The browser will be redirected to index.phppage anyway, no matter the file is successfully uploaded or not. Its just that the popup will appear if the file is of larger size.
index.php无论文件是否成功上传,浏览器都会被重定向到页面。只是文件较大时会出现弹出窗口。

