简体   繁体   English

表单提交后重定向到同一页面中的锚点

[英]Redirect to anchor in same page after form submit

I have a website with a landing page, and at the bottom of the page I have a form.我有一个带有登录页面的网站,在页面底部我有一个表格。 All I want to do is show a validation message and redirect the user to the form again so he can look the message without having to scroll.我要做的就是显示一条验证消息并将用户再次重定向到表单,这样他就可以查看消息而无需滚动。

The code is as follows ( it is on the same page ):代码如下(在同一页上):

  //validation
      if (isset($_POST['submit'])) {                     
          $name = htmlspecialchars(stripslashes(trim($_POST['name'])));

          if (!preg_match("/^[A-Za-zÀ-ÖØ-öø-ÿ]/", $name)) {
              $name_error = 'invalid name';
          }
         //i want to redirect as soon as the validation finishes
        header('Location: http://localhost/myweb/index.php#contact');
      } 

<form id="form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
  <input  type="text" name="name" id="name"> 
     <button type="submit" id="submit" name="submit">Send</button>
</form>

I have tried all of the following:我已经尝试了以下所有方法:

  • Use of window.location.href = 'index.php#contact';使用window.location.href = 'index.php#contact'; in the button ( onclick ) and in the form ( onsubmit )在按钮 ( onclick ) 和表单中 ( onsubmit )
  • Use of the header in multiple parts of the code, also with exit();在代码的多个部分使用header ,也与exit();

However , and here is the key, I do not want to use another page of php only for validation (since I would need to use session_start() and I want to avoid cookies) AND and I do not want to use an AJAX XMLHttp Request.但是,这是关键,我不想仅将 php 的另一页用于验证(因为我需要使用session_start()并且我想避免使用 cookie)并且我不想使用 AJAX XMLHttp 请求.

Is it possible to do it?有可能做到吗?

I'm using #contact in form action like this我在这样的表单操作中使用#contact

<form id="form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>#contact" method="POST">

Did you try this?你试过这个吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM