2011-10-18 58 views
1

我在页面上有一个表单。在里面我有一个元素。如果javascript处于打开状态,我想禁用提交事件。并使用Ajax处理MyMethod中的操作。如何防止提交事件被解雇?如果javascript使用jquery可以防止默认表单提交事件发生

我相信一些形式:event.preventDefault()会做的。但我不知道如何通过这项赛事。

谢谢!

回答

3

你可以订阅.submit()事件的形式,并从它返回false:

$(function() { 
    $('form').submit(function() { 
     // TODO: do your AJAX stuff here 
     // for example ajaxify the form 
     $.ajax({ 
      url: this.action, 
      type: this.method, 
      data: $(this).serialize(), 
      success: function(result) { 
       // TODO: process the result of your AJAX request 
      } 
     }); 

     // this is what will cancel the default action 
     return false; 
    }); 
}); 

或:

$(function() { 
    $('form').submit(function(evt) { 
     evt.preventDefault(); 

     // TODO: do your AJAX stuff here 
     // for example ajaxify the form 
     $.ajax({ 
      url: this.action, 
      type: this.method, 
      data: $(this).serialize(), 
      success: function(result) { 
       // TODO: process the result of your AJAX request 
      } 
     }); 
    }); 
}); 
+0

谢谢!并感谢您添加第一个版本。尽管对我的问题的回答是第二个版本,但第一个版本更好,我实际执行的是。 – Barka