如何在不刷新当前页面的情况下提交表单


How do I submit a form without refreshing the current page?

我有一个相当基本的电子邮件表单

<form name="contactform" method="post" action="send_email.php" id="email_form">
  <div class="ContactHeaders">Name</div>
  <input type="text" name="Name" class="ContactBoxes" id="name"/><br/><br/>
  <div class="ContactHeaders">Email</div>
  <input type="email" name="Email" class="ContactBoxes"/><br/><br/>
  <div class="ContactHeaders">Message</div>
  <div style="width:100%">
    <textarea name="Message" maxlength="1000"></textarea><br/>
  </div>
  <div style="width: 100%">
    <input type="submit" class="Submitbtn" value="Submit">
  </div>
</form>

这是"send_email.php"

<?php
ob_start();
include 'navbar.php';
ob_end_clean();
if(isset($_POST['Email'])) {
  //declare variables
  $Name = $_POST['Name'];
  $Email = $_POST['Email'];
  $Message = $_POST['Message'];
  $complete = 0;
  $email_to = "someone@example.com";
  $email_subject = "Website Contact";
  //check all forms are filled in correctly
  $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+'.[A-Za-z]{2,4}$/';
  if(preg_match($email_exp,$Email)) {
     $complete++;
     }
  $string_exp = "/^[A-Za-z .'-]+$/";
  if(preg_match($string_exp,$Name)) {
     $complete++;
     }
  if(strlen($Message) > 20) {
     $complete++; 
     } 
  //send email if $complete = 4
  if ($complete == 3){
      if (get_magic_quotes_gpc()) {
          $Message = stripslashes($Message);
      }
  $Message =  $Message . "'n'n" . "From " . $Name;
  $headers = 'From: '.$Email."'r'n".
 'Reply-To: '.$Email."'r'n" .
 'X-Mailer: PHP/' . phpversion();
 @mail($email_to, $email_subject, $Message, $headers);
 echo '<script>
     alert("Thank you for contacting me. I will be in touch shortly");
     top.location="index.php";
     </script>';
 }
 else {
     echo '<script>
             alert("The form you submitted is invalid. Please ensure the following: 'n  You have provided a valid email address. 'n  Your phone number is entered correctly. 'n  The message box contains at least 20 characters.")
             history.go(-1)
          </script>';
    }
}
?>

因此,我的问题是,当表单提交到php文件时,浏览器加载php文件,运行代码并返回结果(这不是真正的问题,但这是我不想要的)。然后由java显示警报并返回一个警报(无论如何,在我的代码中)。有没有一种方法可以让它在后台运行代码,这样表单就可以运行php文件,而不必转到它(如果有意义的话)并在同一窗口中返回结果。很明显,我环顾四周,发现了很多关于AJAX的东西,但我并没有真正理解它,也无法让它为我工作

这样做的原因有点复杂,但就我的网站的用户友好性而言,会让事情变得更容易,而且看起来更干净(转到空白页面并显示警报看起来不太好)。

提前感谢您能为我提供的任何帮助:)

$('.Submitbtn').click(function(e) {
    e.preventDefault();
    // do some form validation here
    if form is valid { // from validation above
        var formData = $('#email_form').serialize();
        $.post('send_email.php',{data:formData});
    } else {
        alert('Form no good - fix it!');
        return false;
    }
});

这是一些你可以开始的东西。这是非常基本的,但为开始AJAX冒险提供了必要的基础。

50优秀的AJAX教程