我有一个包含两个字段的表单,我尝试使用 ajax 提交。我有jquery form validator插件,适用于所有其他形式。当我尝试 ajax 提交时,验证似乎不起作用。我使用的脚本是:
$("#add-edit-template").click( function(event)
{
var x;
x = $('.sp-preview-inner').css('backgroundColor');
if(x)
{
hexc(x);
$('#addEditTemplateForm').append("<input type='hidden' name='templateColor' value='"+ color+"' />");
}
$("#addEditTemplateForm").submit(function(e)
{
e.preventDefault();$("div#divLoading").addClass('show');
var postData = $("#addEditTemplateForm").serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
dataType : "html",
success:function(htmlData)
{
$('#ph_widgets').replaceWith(htmlData);
$("#templateSuccess").show();
$("#phButtons").show();
$('#listWidgets').dataTable({"iDisplayLength" : 25, "aaSorting": []});
initDraggabletable("#selectedWidgetTable");
},
error: function( xhr, status, errorThrown )
{
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
},
});
$("div#divLoading").removeClass('show');
e.preventDefault(); //STOP default action
});
});
我需要点击功能,因为我从 div 中获取值,这对我来说也是必需的。我尝试添加
$.validate
({
form : '#addEditTemplateForm'
})
紧接着点击之后以及 ajax 调用之前,但是提交并没有被阻止,验证也没有阻止这一点。我在网上找到了很多解决方案,但没有任何对我有用。有什么办法可以解决这个问题...提前致谢
最佳答案
做这样的事情:
您的 onclick 函数:
$("#add-edit-template").click(function(event) {
var x;
x = $('.sp-preview-inner').css('backgroundColor');
if (x) {
hexc(x);
$('#addEditTemplateForm').append("<input type='hidden' name='templateColor' value='" + color + "' />");
}
$("#addEditTemplateForm").submit(); // trigger submit
});
使用回调函数进行验证
$.validate({
form : '#addEditTemplateForm',
onSuccess : function($form) {
// if your form is valid
$("div#divLoading").addClass('show');
var postData = $("#addEditTemplateForm").serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
dataType: "html",
success: function(htmlData) {
$('#ph_widgets').replaceWith(htmlData);
$("#templateSuccess").show();
$("#phButtons").show();
$('#listWidgets').dataTable({
"iDisplayLength": 25,
"aaSorting": []
});
initDraggabletable("#selectedWidgetTable");
},
error: function(xhr, status, errorThrown) {
console.log("Error: " + errorThrown);
console.log("Status: " + status);
console.dir(xhr);
},
}).always({
$("div#divLoading").removeClass('show');
});
return false; // Will stop the submission of the form
}
})
可以看到很多回调here
关于javascript - jquery 表单验证在 ajax 提交期间不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33360705/