构建了一个简单的 JQuery/Ajax 时事通讯注册表单,然后返回添加 JQuery 验证。我对 javascript/jquery 不太有经验;我已经为此工作了好几天,但毫无想法。
每个脚本单独运行。如果删除提交代码,验证器将正常工作(尽管它可以在指定表单操作 URL 的情况下正常工作)。删除验证器代码后,提交脚本可以完美运行。但是,如果两者都到位,则不会进行任何验证,并且表单仍会通过提交脚本提交。
我所有将两者结合起来的尝试都惨遭失败。
显然我错过了一些相当重要的东西。即使是朝着正确方向最轻微的插入也会受到极大的赞赏
这是完整的代码:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
<!-- form validator -->
<script>
$(document).ready(function(){
// run validator, specifies name of css div that will be displayed
// on error and hide when corrected
$("#nl").validate({
errorContainer: "#errorcontainer",
});
});
</script>
<!-- form submit -->
<script>
$(function() {
// These first three lines of code compensate for Javascript being turned on and off.
// It changes the submit input field from a type of "submit" to a type of "button".
var paraTag = $('input#submit').parent('b');
$(paraTag).children('input').remove();
$(paraTag).append('<input type="button" name="submit" id="submit" value="Submit" />');
$('input#submit').click(function() {
$("#response").css("display", "none");
$("#loading").css("display", "block");
$.ajax({
type: 'GET',
url: 'http://app.icontact.com/icp/signup.php',
data: $("form").serialize(),
complete: function(results) {
setTimeout(function() {
$("#loading").css("display", "none");
$("#response").css("display", "block");
}, 1500);
}
}); // end ajax
});
});
</script>
<style type="text/css">
<!--
#errorcontainer {
display: none;
}
#response {
display: none;
}
-->
</style>
</head>
<body>
<div id="newsletter">
<form id="nl" method="post" action="">
<div id="heading">Sign up for the NCMP newsletter </div>
<div>
<input name="fields_fname" type="text" id="fields_fname" class="required" value="First Name" size="25" />
</div>
<div>
<input name="fields_email" class="example-default-value" type="text" id="fields_email" value="Email address" />
</div>
<b>
<input type="submit" name="submit" id="submit" value="Submit" />
</b>
<div id="response">from submit script - shows on success</div>
<div id="loading"></div>
</form>
</div>
<div id="errorcontainer">from validator script - shows on error</div>
</body>
</html>
谢谢, -鲍勃
最佳答案
看起来 jQuery 验证并未阻止 click
。这是有道理的;我确信该插件可能正在利用 submit
事件。
使用 jQuery 验证时,集成 AJAX 功能的最佳选择可能是在 submitHandler
回调中。所以这应该是简单地移动一些代码的问题:
$("#nl").validate({
errorContainer: "#errorcontainer",
submitHandler: function () {
$("#response").css("display", "none");
$("#loading").css("display", "block");
$.ajax({
type: 'GET',
url: 'http://app.icontact.com/icp/signup.php',
data: $("form").serialize(),
complete: function(results) {
setTimeout(function() {
$("#loading").css("display", "none");
$("#response").css("display", "block");
}, 1500);
}
});
}
});
submitHandler 回调中的代码替换了表单提交的默认操作(即执行普通 HTTP 请求)。
关于JQuery 表单验证和提交脚本冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6887041/