jQuery如何管理HTML表单动作属性的执行


jQuery how to manage HTML form action attribute executing

在执行action属性之前,我需要验证HTML表单。但这让我很难过。请参阅其他声明中的评论,以及返回false后的评论,以解释此问题

$(document).ready(function(){
    $("#ajax-payment-form").submit(function() {
        var str = $(this).serialize();
        $.ajax({
            type: "POST",
            url: templateDir+"/payment_form/payment_process.php",
            data: str,
            success: function(msg) {
                // Message Sent - Show the 'Thank You' message and hide the form
                if(msg == 'OK') {
                    alert("success");
                } else {
                    event.preventDefault(); // I have tried with or without this method
                    alert("fail");
                }
            }
        });
        return false; // when return false, the action will not execute. If false is removed the action will execute, even if event.precentDefault(); is called in the else statement.**
    });                                                         
});

感谢您抽出时间,

Troels

您的ajax调用是异步的。这意味着该函数被执行,并且在继续执行之前不会等待函数的响应。这意味着return false;将始终在ajax函数的结果返回给您之前激发。考虑到您当前的情况,最简单的方法是从success函数中调用this.submit(),但在默认情况下始终调用return false;。这将避免递归,而且异步调用也不再有问题。
$(document).ready(function(){
    $("#ajax-payment-form").submit(function() {
        var str = $(this).serialize();
        $.ajax({
            type: "POST",
            url: templateDir+"/payment_form/payment_process.php",
            data: str,
            context: this, //needed to tell the ajax function that "this" belongs to the form, not the ajax call.
            success: function(msg) {
                // Message Sent - Show the 'Thank You' message and hide the form
                if(msg == 'OK') {
                    alert("success");
                    this.submit(); //it's magic, john.
                } else {
                    //no reason to prevent the default, as the form will automatically return false anyway.
                    alert("fail");
                }
            }
        });
        return false; //just leave this right here.
    });                                                         
});

问题有两个方面:函数调用中没有声明event,成功函数时没有提交表单。提交事件的逻辑应该如下:

  1. 收听<form>元素上的submit事件
  2. 使用e.preventDefault()首先阻止默认表单操作
  3. 进行AJAX调用。根据返回数据的结果,决定是否继续提交表单。我强烈建议不要使用不推荐使用的jqXHR.success函数,而是使用延迟的jqXHR.done()jqXHR.fail()函数

此外,您可以始终使用console.log()检查脚本,而不是依赖于阻止下游代码执行的alert()。这是代码:

$(function(){
    $("#ajax-payment-form input[type='submit']").click(function(e) {
        // Prevent form submission
        e.preventDefault();
        // Serialize data, make AJAX call
        var str = $(this).closest('form').serialize();
        $.ajax({
            type: "POST",
            url: templateDir+"/payment_form/payment_process.php",
            data: str,
            context: this    // So that you can use $(this) later
        }).done(function(msg) {
            // If a response is received from your server
            if(msg == 'OK') {
                 console.log('Validation passed, will submit form');
                 $(this).closest('form').submit();
            } else {
                 console.log('Validation failed, will not do anything more');
            }
        }).fail(function() {
            // Catch ajax errors here
            console.log('AJAX error');
        });
    });                                                         
});