php - 如何在重定向到同一页面时在php中聚焦页面的特定部分
问题描述
我在$_SERVER['PHP_SELF']
提交表单后使用将表单发布到同一页面我需要关注(滚动到)表单所在页面的页脚;尝试在条件块外调用标头,提示错误“ERR_TOO_MANY_REDIRECTS”,如果我将标头调用放在条件块内。重定向工作,也关注所需的部分,但其余的 php 代码不起作用
<?php
$popupMessage = '';
if(isset($_POST['submit'])){
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = htmlspecialchars($_POST['message']);
if(!empty($name) && !empty($email) && !empty($message)){
//code for sending mail
$popupMessage = 'Email Sent Successfully';
}
else{
$popupMessage = 'Please fill in all the fields';
}
// header('Location: test.php#footer');
}
?>
<html>
<center>
<div style="width:100%; height:1200px;"><h1>please scroll down</h1></div>
<div id="footer" style="border:1px solid grey">
<span><?php echo $popupMessage ?></span>
<form id="form-location" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<p><input type="text" name="name" placeholder="Your Name"></p>
<p><input type="text" name="email" placeholder="Your email"></p>
<p><textarea name="message" placeholder="Your message"></textarea></p>
<button type="submit" name="submit">Send</button>
</form>
</div>
</center>
</html>
解决方案
看起来您的重定向正在无条件执行。如果它像这样提交,请将其放在处理表单的条件中:
if (isset($_POST['submitted'])) {
// Process the form normally.
header('Location: ' . $_SERVER['PHP_SELF'] . '#myElt');
exit;
}
标Location
头将创建一个新请求,因此如果您想保留发布数据,此解决方案将不起作用。你可以做的是改变你的form action
:
<form action="<?php echo $_SERVER['PHP_SELF'] ?>#footer" method="post">
推荐阅读
- java - 使用 Apache POI 获取 Excel 填充颜色
- database-design - 如何为博客设计数据库(带有系列文章)?
- python - Pandas df to csv 插入空行
- gtk - 在 Linux 上 GTK+3 的 GtkDrawingArea 中拦截 X11 KeyPress 事件
- php - codeigniter中的多个加入不起作用
- php - 配置 apache 运行 node.js 应用
- html - 如何工作位置粘相对窗口?
- php - PHPMailer 中奇怪的 $_POST 行为
- c# - 在 MVC 上的 Microsoft 站点上使用 WordprocessingDocument 基础后收到消息“MEMORY STREAM IS NOT EXPANDABLE”
- jquery - 在引导程序中的导航栏上方自动隐藏警报