jQuery Validate:如何在表单有效后发布()?

时间:2013-01-10 05:39:52

标签: jquery jquery-validate

这有效:

 $('#contestform').on('submit', function(e) {
     $.post( '/', $(this).serialize(), function(response){
    console.log(response);
},'json' );
    e.preventDefault();
});

这是有效的

jQuery("#contestform").validate();

但我无法弄清楚如何让他们一起工作。我希望顶级代码中的内容只有在单击提交并且表单有效时才会发生。我试过http://docs.jquery.com/Plugins/Validation/validate#toptions的东西,但我想我不明白。我让它在某一点上工作,但你必须点击提交两次。

有一点是,如果我可以帮助它,我想将post()内容保存在一个单独的函数中,因为这两部分将来自php的不同部分。

编辑1 试过这个,没有工作(在表格下) (通过不工作,我的意思是它正在提交,而不是ajax)

function postForm(e) {
     jQuery.post( '/', $(this).serialize(),   function(response){
    console.log(response);
},'json' );
    e.preventDefault();
}
jQuery("#contestform").validate({submitHandler: postForm});

EDIT2 好吧,我使用了jQuery.Form插件 http://www.malsup.com/jquery/form/#ajaxSubmit 不过,我想在上面的代码中知道我做错了什么。

function  showResponse(responseText, statusText, xhr, $form){
    console.log(responseText);
}
var soptions = { 
        success: showResponse ,
        dataType: 'json'
        };

jQuery("#contestform").validate({
   submitHandler: function(form) {
     jQuery(form).ajaxSubmit(soptions);
        return false; // always return false to prevent standard browser submit and page navigation 
   }
});

2 个答案:

答案 0 :(得分:4)

submitHandler函数的参数不是jQuery事件,它是表单DOM对象。所以

  1. 当您调用e.preventDefault()时,您的代码将抛出错误;
  2. 调用$(form).serialize(),而不是$(this).serialize()
  3. 让你的edit1正常工作

    <script>
    $(function () {
        $("form").validate({
            submitHandler: function (form) {
                $.post('/your_url/',
                $(form).serialize(), function (response) {
                    console.log(response);
                }, 'json');
            } 
        });
    });
    </script>
    

    或保持postForm功能分开

    <script>
    $(function () {
    
        function postForm(form) {
            $.post('/your_url/',
                $(form).serialize(),
                function (response) { console.log(response); }, 
                'json');
        }
    
        jQuery("form").validate({
            submitHandler : postForm
        });
    });
    </script>
    

答案 1 :(得分:1)

function postForm (e) {
    $.post(...);
}
jQuery("#contestform").validate({submitHandler: postForm});
相关问题