提交由 jquery 生成的表单

Submit a form generated by jquery

本文关键字:表单 jquery 提交      更新时间:2023-09-26

我的网站上的登录表单使用带有jquery-modal的覆盖/模式显示(http://kylefox.ca/jquery-modal/examples/)

我正在使用ajax + php来验证表单。如果验证通过,则应提交表单。

我可以停止提交以进行验证(使用返回 false),并且验证本身工作正常。但是我不知道如何提交表格

我尝试了许多幼稚的变体:返回true,$theform.submit(),$("body").unbind("#myloginform")等等。 但到目前为止没有运气

$("body").on("submit", "#myloginform", function() {
    $theform = $(this);
    $.ajax({
        url: "login_check.php",
        type: "POST",
        cache: false,
        timeout: 9000,
        data: $theform.serialize(),
        dataType: "json",
        success: function(data) {
            if (data) {
                if (data.status == "ok") {
                    alert("success! now the form can be submitted");
                    // SUBMIT THE FORM (instead of the alert)
                } else {
                    $("body #loginstatus").html(data.status);
                }
            } else {
                alert("Error bla bla.");
            }
        },
        error: function(e) {
            alert("Error (ajax) bla bla.");
        }
    });
    return false;
});

要提交 FORM,可以调用 js 原生提交方法:

document.getElementById('myloginform').submit();

查看变体:

$('#myloginform')[0].submit();
$('#myloginform').get(0).submit();

另一种方法是将 ajax 的选项设置为 this context

$.ajax({
     context: this,
     ...,
});

然后在成功回调中,使用以下方法提交表单:

this.submit();

编辑:我看到您已经在使用变量引用,因此在您的情况下,您也可以使用:

$theform[0].submit();

所有这些代码段都不会触发 jQuery 提交处理程序,从而避免循环引用错误。

另一种方法:

var checkValid = false;
$("body").on("submit", "#myloginform", function () {
    $theform = $(this);
    if (!checkValid) {
        $.ajax({
            url: "login_check.php",
            type: "POST",
            cache: false,
            timeout: 9000,
            data: $theform.serialize(),
            dataType: "json",
            success: function (data) {
                if (data) {
                    if (data.status == "ok") {
                        alert("success! now the form can be submitted");
                        // Everything is OK
                        checkValid = true;
                        $theform.submit();// Next time, no validation process, just natural send of the form.
                    } else {
                        $("body #loginstatus").html(data.status);
                    }
                } else {
                    alert("Error bla bla.");
                }
            },
            error: function (e) {
                alert("Error (ajax) bla bla.");
            }
        });
        return false;
    }
});

既然你使用的是jQuery,我建议你看看jQuery提交函数

http://api.jquery.com/submit/