2011-10-18 135 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