我正在使用jquery验证插件来验证ajax提交的表单。如果服务器端存在错误,则ajax调用将返回表单的html。
问题是如果这种情况发生在ajax上就不再起作用了。我需要一些像jquery验证插件一样的“live”jquery函数。
这是我的代码:
$('#myform').validate({
submitHandler: function(form) {
formData = $(form).serialize();
$.ajax({
type: "POST",
url: form.action,
data: formData ,
dataType: 'json',
success: function(response){
if(response.status == "success")
window.location.reload(true);
else
$('#myformdiv').html(response.html);
},
error: function(response){
}
});
return false;
}
});
答案 0 :(得分:3)
在ajax加载表单验证上花了很长时间来探讨这个主题,帮助解决我的问题的唯一解决方案就是这个讨论线程:
加载新表单后调用以下行。如果新表单在jquery对话框中,则在打开对话框后调用它。
$.validator.unobtrusive.parse("#myAjaxLoadedFormId");>
答案 1 :(得分:1)
您需要在html内部包含后重新运行验证脚本。
我有同样的问题。当我在页面加载时从服务器加载它但在ajax验证消失后,表单验证工作正常。所以我在将表单嵌入到html和它的工作后添加了这段代码。
$('#myform').validate({
submitHandler: function(form) {
formData = $(form).serialize();
$.ajax({
type: "POST",
url: form.action,
data: formData ,
dataType: "html",
cache: false,
success: function (data) {
$('#myformdiv').html(data);
$.getScript("/Scripts/jquery.validate.unobtrusive.js");
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
return false;
}
});
答案 2 :(得分:-3)
你应该考虑阅读this question和我对它的回答