提交由 jquery 生成的表格

Submit a form generated by jquery

我网站上的登录表单使用 overlay/modal 和 jquery 模式 (http://kylefox.ca/jquery-modal/examples/)

显示

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

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

我尝试了很多天真的变体:return 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 的 context 选项设置为 this:

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

然后在成功回调中,提交 FORM 使用:

this.submit();

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

$theform[0].submit();

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

由于您使用的是 jQuery,我建议您查看 jQuery 提交功能

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

另一种方法:

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;
    }

});