Javascript 提交jquery生成的表单
我的站点上的登录表单使用jquery modal()的覆盖/模式显示 我正在使用ajax+php验证表单。如果验证通过,则应提交表格 我可以停止提交进行验证(使用returnfalse),验证本身工作正常。但是我不知道如何提交表格 我尝试了许多简单的变体:return true、$theform.submit()、$(“body”)、unbind(#myloginform)等等。。但到目前为止没有运气Javascript 提交jquery生成的表单,javascript,jquery,ajax,forms,Javascript,Jquery,Ajax,Forms,我的站点上的登录表单使用jquery modal()的覆盖/模式显示 我正在使用ajax+php验证表单。如果验证通过,则应提交表格 我可以停止提交进行验证(使用returnfalse),验证本身工作正常。但是我不知道如何提交表格 我尝试了许多简单的变体:return true、$theform.submit()、$(“body”)、unbind(#myloginform)等等。。但到目前为止没有运气 $("body").on("submit", "#myloginform", function
$("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;
});
要提交表单,可以调用js native submit方法:
document.getElementById('myloginform').submit()代码>
参见变体:
$('#myloginform')[0].submit();
$('#myloginform').get(0).submit();
另一种方法是将ajax的context
选项设置为this
:
$.ajax({
context: this,
...,
});
然后在成功回调中,使用以下命令提交表单:
this.submit();
编辑:我看到您已经在使用变量引用,因此在您的情况下,您也可以使用:
$theform[0].submit();
所有这些代码片段都不会触发jQuery提交处理程序,从而避免了循环引用错误。既然您使用的是jQuery,我建议您检查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;
}
});
尽管我没有找到任何说明submit不能处理委托事件的参考资料。如果可能的话,我会试着做一个直接的、均匀的处理和测试。类似这样的$(“#myloginform”)。在(“submit”,function()
@ClaudioRedi)上,我不能直接引用这样的表单,因为它是由javascript创建/启动的(我猜)。我很好奇,这个方法不会触发事件,然后jQuery会处理它吗?太棒了。我想我会使用最后一个:$theform[0]。submit();(稍微优雅一点吗?)。无法使上下文正常工作。Thanks@acontell那么jQuery将处理它是什么意思呢?
?调用本机提交方法不会触发jQuery上绑定的提交处理程序FORM@acontell我没有把它当成“个人的”,真的没有;)@mowgli因为使用$theform.submit();
将重新触发相同的jQuery处理程序。现在可以在调用它之前解除绑定此事件,例如:$theform.off('submit').submit()
这并没有以任何方式回答问题,尝试一下,你会发现它显然没有回答问题。不应该跳过ajax部分,为什么要这样建议?你建议表单提交多次?第一次尝试提交时,它会验证。当ajax完成时,它会将变量设置为true并提交。Th事件再次触发,但这次变量为true,跳过验证并提交表单