在以下代码中,我有一个联系表单,并且在该表单中有一个电子邮件验证脚本。验证的结果是,我希望错误消息显示在称为“确认”的div中,而无需重新加载页面。另外,如果电子邮件有效,则将发送邮件,并且我希望在同一div确认中显示“谢谢”消息。问题是我该怎么做才能防止重新加载页面并使错误消息或感谢消息显示在确认div中?

<html>
<body>
<?php
function spamcheck($field) {
  // Sanitize e-mail address
  $field=filter_var($field, FILTER_SANITIZE_EMAIL);
  // Validate e-mail address
  if(filter_var($field, FILTER_VALIDATE_EMAIL)) {
    return TRUE;
  } else {
    return FALSE;
  }
}
?>

<?php
if (!isset($_POST["submit"])) {
  ?>
  <form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
  From: <input type="text" name="from"><br>
  Subject: <input type="text" name="subject"><br>
  Message: <textarea rows="10" cols="40" name="message"></textarea><br>
  <input type="submit" name="submit" value="Submit Feedback"><br>
  <div id="confirmation" style="display:none" align="center"></div>
  </form>
  <?php
} else {  // the user has submitted the form
  // Check if the "from" input field is filled out
  if (isset($_POST["from"])) {
    // Check if "from" email address is valid
    $mailcheck = spamcheck($_POST["from"]);
    if ($mailcheck==FALSE) {
      echo"
      <script>
        document.getElementById('confirmation').text ='invalid email';
      </script>";
    } else {
      $from = $_POST["from"]; // sender
      $subject = $_POST["subject"];
      $message = $_POST["message"];
      // message lines should not exceed 70 characters (PHP rule), so wrap it
      $message = wordwrap($message, 70);
      // send mail
      mail("nawe11@gmail.com",$subject,$message,"From: $from\n");
      echo"
      <script>
        document.getElementById('confirmation').text ='Thank you';
      </script>";
    }
  }
}
?>
</body>
</html>


谢谢

最佳答案

<input type="text" name="from" id ="from">


通话示例:

var request = $.ajax({
  url: "file.php",
  type: "POST",
  data: { email : $('#from').val() }
});

request.done(function( msg ) {
  //handle HTML
});

request.fail(function( jqXHR, textStatus ) {
  //Handle problem at server side
});


PHP方面

<?php

$email = $_POST["email"]

function spamcheck($field) {
  // Sanitize e-mail address
  $field=filter_var($field, FILTER_SANITIZE_EMAIL);
  // Validate e-mail address
  if(filter_var($field, FILTER_VALIDATE_EMAIL)) {
    return 'valid';
  } else {
    return 'no_valid';
  }
}

echo spamcheck($email);

10-07 19:10
查看更多