PHP 表单 - 提交时停留在同一页面

问题描述:

我有一个位于文件 contact.html 中的 PHP 表单.

I have a PHP form that is located on file contact.html.

表单是从文件 processForm.php 处理的.

The form is processed from file processForm.php.

当用户填写表单并点击提交时,processForm.php 发送电子邮件并将用户引导至 - processForm.php在该页面上显示一条消息成功!您的消息已发送."

When a user fills out the form and clicks on submit, processForm.php sends the email and direct the user to - processForm.php with a message on that page "Success! Your message has been sent."

我对 PHP 了解不多,但我知道要求这样做的操作是:

I do not know much about PHP, but I know that the action that is calling for this is:

// Die with a success message
die("<span class='success'>Success! Your message has been sent.</span>");

如何将消息保留在表单 div 中而不重定向到processForm.php 页面?

How can I keep the message inside the form div without redirecting to the processForm.php page?

如果需要,我可以发布整个 processForm.php,但它很长.

I can post the entire processForm.php if needed, but it is long.

为了在提交时保持在同一页面上,您可以将 action 留空 (action="") 到表单标签中,或者完全不使用它.

In order to stay on the same page on submit you can leave action empty (action="") into the form tag, or leave it out altogether.

对于消息,创建一个变量 ($message = "Success! You enter: ".$input;") 然后在页面中你想要消息的地方回显变量与 <?php echo $message; ?> 一起出现.

For the message, create a variable ($message = "Success! You entered: ".$input;") and then echo the variable at the place in the page where you want the message to appear with <?php echo $message; ?>.

像这样:

<?php
$message = "";
if(isset($_POST['SubmitButton'])){ //check if form was submitted
  $input = $_POST['inputText']; //get input text
  $message = "Success! You entered: ".$input;
}    
?>

<html>
<body>    
<form action="" method="post">
<?php echo $message; ?>
  <input type="text" name="inputText"/>
  <input type="submit" name="SubmitButton"/>
</form>    
</body>
</html>