7

如何在同一页面上处理表单与使用单独的流程页面。现在对于注册、评论提交等,我使用第二个页面来验证数据,然后提交并路由回 home.php。我怎样才能使它在提交时,页面本身验证而不是使用第二个页面。

4

6 回答 6

14

你可以告诉表单提交给 PHP 自己,然后检查$_POST表单处理的变量。这种方法非常适合错误检查,因为您可以设置一个错误,然后让表单重新加载用户之前提交的任何信息(即他们不会丢失提交)。

单击“提交”按钮时,它会将信息发布到同一页面,并在顶部运行 PHP 代码。如果发生错误(根据您的检查),表单将为用户重新加载,显示错误以及用户在字段中提供的任何信息。如果没有发生错误,您将显示确认页面而不是表单。

<?php
//Form submitted
if(isset($_POST['submit'])) {
  //Error checking
  if(!$_POST['yourname']) {
    $error['yourname'] = "<p>Please supply your name.</p>\n";
  }
  if(!$_POST['address']) {
    $error['address'] = "<p>Please supply your address.</p>\n";
  }

  //No errors, process
  if(!is_array($error)) {
    //Process your form

    //Display confirmation page
    echo "<p>Thank you for your submission.</p>\n";

    //Require or include any page footer you might have
    //here as well so the style of your page isn't broken.
    //Then exit the script.
    exit;
  }
}
?>

<form method="post" action="<?=$_SERVER['PHP_SELF']?>">
  <?=$error['yourname']?>
  <p><label for="yourname">Your Name:</label><input type="text" id="yourname" name="yourname" value="<?=($_POST['yourname'] ? htmlentities($_POST['yourname']) : '')?>" /></p>
  <?=$error['address']?>
  <p><label for="address">Your Address:</label><input type="text" id="address" name="address" value="<?=($_POST['address'] ? htmlentities($_POST['address']) : '')?>" /></p>
  <p><input type="submit" name="submit" value="Submit" /></p>
</form>
于 2011-01-24T15:03:48.347 回答
7

最简单的构造就是检测$_POST数组是否不为空

if(isset($_POST['myVarInTheForm'])) {
  // Process the form
}

// do the regular job
于 2011-01-24T14:56:09.790 回答
2

您可以检查它是否是页面代码中的 POST 请求,然后检查数据。如果是 GET 请求 - 只需显示表单。

但请记住,在通过 GET 请求提供的不同页面上显示成功的表单提交结果是一种很好的做法,即任何成功的表单 POST 都应该通过重定向到成功页面来回答。

于 2011-01-24T14:56:39.383 回答
1

您当然可以探索查看 AJAX 请求,在其中您将对处理程序脚本进行异步调用,然后使用成功消息更新发送页面。这给人一种“相同页面处理”的印象,即页面不必刷新。

但是,这实际上取决于您要达到的效果。

于 2011-01-24T15:02:58.390 回答
0

我保存了一条感谢消息并使用会话变量进行了刷新。

if(!is_array($error)){
    $_SESSION['message'] = 'Thank You!';
    header('Location: yourpage.php');
    exit();
} 

然后在表格顶部使用它:

if(isset($_SESSION['message'])){ 
    echo $_SESSION['message'];
    unset($_SESSION['message'];
} 

这应该刷新页面并显示消息,然后如果他们刷新页面,会话变量为空,因此不会显示谢谢。这称为闪存消息。

于 2014-06-01T19:56:31.850 回答
0

@Michael Irigoyen: It works fine, but on first rn/load, it shows:

"Notice: Undefined variable: error in C:\xampp\htdocs\same_page.php on line 28"

How to handle this notice?

Got it now: "Used isset, @ etc. to supress errors..." "Works like a charm!!!" "Now i'll try it on my code..."

于 2011-07-25T05:42:52.800 回答