twitter-bootstrap 使用 Bootstrap validator.js 和 Jquery ajax 表单发布
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29196445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Bootstrap validator.js with Jquery ajax form post
提问by Acyra
I'm trying to use this validator https://github.com/1000hz/bootstrap-validatorfor client-side checking and then allowing the ajax submission of an entire form. I can't find an example in the docs and my current code doesn't work, it reloads the whole page with the values as a GET query string. Any thoughts? Thanks!
我正在尝试使用此验证器https://github.com/1000hz/bootstrap-validator进行客户端检查,然后允许 ajax 提交整个表单。我在文档中找不到示例并且我当前的代码不起作用,它使用值作为 GET 查询字符串重新加载整个页面。有什么想法吗?谢谢!
$('#send-form').validator().on('submit', function (e) {
if (e.isDefaultPrevented()) {
// handle the invalid form...
} else {
// everything looks good!
$.post( "/post/ajax",
$( "#send-form" ).serialize(),
function( data ) {
$( "#ajax-result" ).html( data );
});
}
});
回答by Dhiraj
Add e.preventDefault()in the else statement.
e.preventDefault()在 else 语句中添加。
If you look at #227 in the source code, the validator prevents form submission if the form is invalid. Hence e.isDefaultPrevented()can be used to check if the form is invalid.
如果您查看源代码中的#227,如果表单无效,验证器会阻止表单提交。因此e.isDefaultPrevented()可用于检查表单是否无效。
The form's default action is carried out if the form is valid which is submitting the form (why the page reloads). Since you need to do an ajax you should stop default action by e.preventDefault()
如果表单有效并提交表单(页面重新加载的原因),则执行表单的默认操作。由于您需要执行 ajax,因此您应该通过以下方式停止默认操作e.preventDefault()
$('#send-form').validator().on('submit', function (e) {
if (e.isDefaultPrevented()) {
alert('form is not valid');
} else {
e.preventDefault();
alert('form is valid');
// your ajax
}
});
Here is a demo
这是一个演示
Hope this helps
希望这可以帮助

