大家好,我的一个插件有问题。我正在使用这个jquery form valdiation验证我的表单,但如果我有 AJAX 调用来提交数据,则验证将被忽略。我尝试设置一个全局变量并在 AJAX 调用中创建一个控制语句来停止提交它,但是当我这样做时,验证有效,但无法提交数据。
验证
var isValid = 0;
$.validate({
form : '#comment-form',
onSuccess : function() {
isValid = 1;
return false;
},
validateOnBlur : false,
errorMessagePosition : 'top',
scrollToTopOnError : false,
});
AJAX提交数据:
$(document).ready(function() {
if (isValid == 1)
{
$("#submitComment").click(function (e) {
e.preventDefault();
var name = $("#nameTxt").val();
var comment = $("#commentTxt").val(); //build a post data structure
var article = $("#articleID").val();
var isFill = $("#isFillTxt").val();
jQuery.ajax({
type: "POST", // Post / Get method
url: "<?php echo site_url('articles/create_comment/'); ?>", //Where form data is sent on submission
dataType:"text", // Data type, HTML, json etc.
data: "body=" + comment + "&name=" + name + "&article_id=" + article + "&isFillCheck=" + isFill, //Form variables
success:function(response){
$("#responds").append(response);
document.getElementById("commentTxt").value="";
document.getElementById("nameTxt").value="";
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
});
}
});
最佳答案
您的代码无法正常工作的原因是因为 isValid 的值为 0,而您在文档仍在加载时要求它等于 1。
针对您的问题 - 您可以以仅在验证成功后才触发 ajax 调用的方式链接事件。简而言之:
function sendForm()
{
var name = $("#nameTxt").val();
var comment = $("#commentTxt").val(); //build a post data structure
var article = $("#articleID").val();
var isFill = $("#isFillTxt").val();
jQuery.ajax({
type: "POST", // Post / Get method
url: "<?php echo site_url('articles/create_comment/'); ?>", //Where form data is sent on submission
dataType:"text", // Data type, HTML, json etc.
data: "body=" + comment + "&name=" + name + "&article_id=" + article + "&isFillCheck=" + isFill, //Form variables
success:function(response){
$("#responds").append(response);
document.getElementById("commentTxt").value="";
document.getElementById("nameTxt").value="";
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
}
$.validate({
form : '#comment-form',
onSuccess : function() {
sendForm();
return false;
},
validateOnBlur : false,
errorMessagePosition : 'top',
scrollToTopOnError : false,
});
只需确保整个过程发生在文档就绪功能的内部即可。
关于javascript - 在验证完成之前停止提交?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27095413/