简体   繁体   English

Rails 3 Jquery验证插件

[英]Rails 3 Jquery validate plugin

I have this js code 我有这个js代码

$(".new_milestone").validate({
     submitHandler: function(form) {
    $(form).submitWithAjax();
   },
     errorPlacement: function(error, element) {
        error.insertBefore(element);
     }
   });  

It all works, errorPlacement and the submitWithAjax function. 一切正常,errorPlacement和submitWithAjax函数。 But when I post the form the second time without reloading the page, the form gets posted two times. 但是,当我第二次发布表单而不重新加载页面时,该表单被发布了两次。 Next time 3 times and so on. 下次3次,依此类推。

When I do this 当我这样做时

 $(".new_milestone").validate({
             errorPlacement: function(error, element) {
                error.insertBefore(element);
             }
           });
$(".new_milestone").submitWithAjax(); 

It works, but it does the ajax post even if the form is not valid. 它可以工作,但是即使表单无效,它也可以执行ajax发布。

The submitWithAjax function looks like this (thanks Ryan Bates) SubmitWithAjax函数如下所示(感谢Ryan Bates)

jQuery.fn.submitWithAjax = function() {
  this.submit(function() { 

    $.post(this.action, $(this).serialize(), null, "script");
    $('.spinning').show(); 
    $("#dialog_form").dialog("close")
    return false;
  })
  return this;
};

Any ideas on stopping this behavior? 有任何停止这种行为的想法吗?

This is happening because your ssubmitWithAjax function doesn't * actually* submit (fire the event), it attaches a submit handler for when the submit happens (which the normal behavior is doing)...since you're calling it in a submit situation, just remove the handler wrapper and actually submit, like this: 发生这种情况是因为您的ssubmitWithAjax函数实际上并未*提交(触发事件),它会在submit发生时(正常行为正在执行) 附加一个提交处理程序 ...因为您是在提交中调用它在这种情况下,只需删除处理程序包装并实际提交即可,如下所示:

jQuery.fn.submitWithAjax = function() {
  $.post(this.attr("action"), this.serialize(), null, "script");
  $('.spinning').show(); 
  $("#dialog_form").dialog("close")
  return false;
};

Note the .attr("action") change, because this is not a jQuery object, not a <form> DOM element since it's directly in the plugin. 注意.attr("action")更改,因为this不是jQuery对象,也不是<form> DOM元素,因为它直接在插件中。


Previously, you were attaching an additional submit handler each time, which is why you get 1, 2, 3.... submits, by just calling the submit code you want, this won't happen, since inside submitHandler is the valid place to go ahead and submit anyway. 以前,你在安装一个附加 submit每次处理程序,这就是为什么你会得到1,2,3 ....提交,通过只调用提交你想要的代码,这将不会发生,因为里面submitHandler是有效的地方继续进行提交。

As an aside, the callback function to $.post() is optional, so you can leave off that null, and it'll function properly. $.post()$.post()的回调函数是可选的,因此您可以省略该null,它将正常运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM