我有这个js代码

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


一切正常,errorPlacement和submitWithAjax函数。但是,当我第二次发布表单而不重新加载页面时,表单被发布了两次。下次3次,依此类推。

当我这样做时

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


它可以工作,但是即使表单无效,它也可以执行ajax发布。

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;
};


有任何停止这种行为的想法吗?

最佳答案

发生这种情况是因为您的ssubmitWithAjax函数实际上不是*提交(触发事件),它会在submit发生时(正常行为正在执行)附加一个提交处理程序...因为您正在调用在提交情况下,只需删除处理程序包装并实际提交即可,如下所示:

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


注意.attr("action")的变化,因为this不是jQuery对象,也不是<form> DOM元素,因为它直接在插件中。



以前,您每次都附加一个附加的submit处理程序,这就是为什么您仅通过调用所需的提交代码来获得1,2,3 ....提交的原因,因为在submitHandler内部是继续进行提交的有效地点。

顺便说一句,$.post()的回调函数是可选的,因此您可以省略该null,,它将正常运行。

关于javascript - Rails 3 jQuery验证插件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4668094/

10-12 12:35
查看更多