首页 > 解决方案 > 如何在重定向到同一页面时在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>

标签: php

解决方案


看起来您的重定向正在无条件执行。如果它像这样提交,请将其放在处理表单的条件中:

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">

推荐阅读