提交表单时,浏览器加载php文件,该文件包含处理表单的代码


On form submission the browser loads the php file that had the code for handling the form

我正在写我的第一个php代码。。。我正在尝试提交表格。
我有两个php文件。index.php(包含表单)和process.php(包含处理表单的方法)
但在提交表单时,浏览器会转到process.php,因此不会显示任何内容。我正试图在index.php.中呼应这个结果

请记住,这是我的第一个php代码…:-)

这是index.php

<!DOCTYPE html>
<html>
<?php
  include 'process.php';
  $newletter1 = new newsletter();
?>
  <head>
    <meta charset="utf-8">
  <title></title>
  </head>
  <body>
    <form action="process.php" method="post">
      <input type="text" name="email" placeholder="Your Email Address..."><br><br>
      <input type="submit">
    </form>
    <h4><?php $newletter1 -> abc(); ?></h4>
  </body>
  </html>

这是process.php

class newsletter
{
  public function abc()
  {
    if (isset($_POST["email"])) {
      $input = $_POST["email"];
      if (empty($input)) {
        echo "Please provide an email address!";
      }else{
        echo "Thanks for subscribing " . $input;
      }
    }else{
      echo "ELSE is running...";
    }
  }
}

您的脚本process.php只是一个类定义。

一个类什么都不做,除非它被实例化并调用了一个方法。

当您在index.php中包含它并实例化它时,我建议更改<form>标记,使其自己运行,让href=""来执行此操作。

<?php
  // run this only if we are being set info by the user
  // so not when the form is first loaded.
  $to_show_later = '';
  if ($_SERVER['REQUEST_METHOD'] == 'POST' ) {
      include 'process.php';
      $newletter1 = new newsletter();
      $to_show_later = $newsletter1->abc();
  }
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
    <form action="" method="post">
      <input type="text" name="email" placeholder="Your Email Address..."><br><br>
      <input type="submit">
    </form>
    <h4><?php echo $to_show_later; ?></h4>
</body>
</html>

直接从类方法中回显也是一种不好的做法,因此请更改此项,使其返回数据。

class newsletter
{
  public function abc()
  {
    $reply = '';
    if (isset($_POST["email"])) {
      $input = $_POST["email"];
      if (empty($input)) {
        $reply = "Please provide an email address!";
      }else{
        $reply = "Thanks for subscribing " . $input;
      }
    }else{
      $reply = "ELSE is running...";
    }
    return $reply;
  }
}

在您的进程中。php将其替换为:

if (isset($_POST["email"])) {
      $input = $_POST["email"];
      if (empty($input)) {
        echo "Please provide an email address!";
      }else{
        echo "Thanks for subscribing " . $input;
      }
    }else{
      echo "ELSE is running...";
    }

它会起作用,并且您不必包含process.php来提交仅表单