将Bootstrap validator.js与Jquery ajax表单post结合使用



我正在尝试使用这个验证器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 );
            });
       }
   });

在else语句中添加e.preventDefault()

如果您查看源代码中的#227,如果表单无效,验证器会阻止表单提交。因此,e.isDefaultPrevented()可以用于检查表单是否无效。

如果提交表单的表单有效(页面重新加载的原因),则执行表单的默认操作。由于您需要执行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
    }
});

这是一个演示

希望这能帮助

最新更新