jQuery验证和AJAX提交表单如何编写e.preventDefault();

时间:2017-01-11 14:39:55

标签: javascript php jquery html ajax

您好我使用AJAX提交表单和jQuery Validate。

问题是e.preventDefault();我不知道在这种情况下如何写它。

问题是:它将通过常用方法和AJAX方法两次提交表单,导致MySQL插入两次。

<?php 
$servername = "localhost";
$username = "root";
$password = "1234";
$dbname = "test";

$conn = mysqli_connect($servername, $username, $password, $dbname);

if ($_POST) {
    $firstname = $_POST['firstname'];
    $lastname = $_POST['lastname'];
    $sql = "INSERT INTO test (firstname, lastname) VALUES ('$firstname', '$lastname')";
    mysqli_query($conn, $sql);
    mysqli_close($conn);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.js"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/additional-methods.js"></script>
</head>
<body>
<div id="kuy"> </div>
<div id="lastname"></div>
    <form id="myform" action="this_page.php" method="post">
        Firstname : <input type="text" name="firstname" required> <br>
        Lastname : <input type="text" name="lastname" required> <br>
        <input type="submit" value="Submit">
    </form>

    <script>
        $("#myform").validate({
          rules: {
            // simple rule, converted to {required:true}
            firstname: "required",
            // compound rule
            lastname: {
              required: true,
              email: true
            }
          },
          submitHandler: function(form) {
            $.ajax({
                type : "POST",
                url : 'this_page.php',
                //dataType : 'json', // Notice json here
                data : $(form).serialize(), // serializes the form's elements.
                success : function (data) {
                   alert('success'); // show response from the php script.

                }
            });

            form.preventDefault();
          }
        });
    </script>
</body>
</html>

1 个答案:

答案 0 :(得分:3)

您可以单独绑定submit事件,因为在表单有效之前它不会发生

$("#myform").validate({
   rules: {
   // simple rule, converted to {required:true}
   firstname: "required",
   // compound rule
   lastname: {
      required: true,
      email: true
   }
}).on('submit', function(e) {
     e.preventDefault();
     var $form = $(this);
     $.ajax({
        type : "POST",
        url : 'this_page.php',
        //dataType : 'json', // Notice json here
        data : $form.serialize(), // serializes the form's elements.
        success : function (data, response) {
            alert(response); // show response from the php script.
        }
     });
});

有趣的是,在docs中,您无法找到有关此内容的信息......