Ajax 验证在表单提交事件中入侵表单提交


Ajax Validation intrupt the form submit on form submit event

嗨,我在表单重定向

到其操作目标时遇到问题,验证 ajax 中断了表单重定向,这是我的代码,我只是将帖子提交到表单操作位置也重定向到该位置。

$("form").submit(function(e){
  jQuery.ajax({
     type : "post",
     url : "validate.php",
     dataType : "json",
     data : {email : 'example@domain.com'},
     success: function(response) { 
        if(response.status == '1'){
          //Email is valid want to continue form submit and redirect , but it is not 
        }else{
           e.preventDefault();
           //return false
        }
     }
  });
})
您可能需要

创建一个单独的函数submit表单作为验证 ajax 进程的回调,并将序列化数据传递给它,如下所示:

function submitForm(serializedData) {
    jQuery.ajax({
        ur: "{your form action processing file}",
        type: "POST",
        data: serializedData,
        success: function (data, textStatus, xhr) {
            console.log("form submitted "+xhr.status) // 201 if everything OK
            // optionally reload the page
            window.location.reload(true);
        }
    });
}
jQuery(document).ready(function ($) {
    // validate form
    $("#myForm").on("submit", function (event) {
        // prevent form from being submitted
        event.preventDefault();
        // collect your form data to be submitted  :
        var serializedData = $("#myForm").serializeArray();
        $.ajax({
            url : "validate.php",
            type: "POST",
            cache: false,
            dataType : "json",
            data : {email : 'example@domain.com'},
            success: function (response) {
                if(response.status == '1'){
                    // email is valid so submit the form
                    submitForm(serializedData);
                } // you don't need an else statement since we already used event.preventDefault() before the ajax call
            },
            error: function () {
                console.log("ajax validation error");
            }
        })
    }); // on submit    
}); // ready

请注意,我们为正在处理的表单分配了一个选择器 ( #myForm )。