2012-03-04 121 views
16

我正在使用以下jQuery代碼通過AJAX提交表單。通過jQuery中的AJAX提交表單

jQuery('form.AjaxForm').submit(function() {    
     $.ajax({ 
      url  : $(this).attr('action'), 
      type : $(this).attr('method'), 
      dataType: 'json', 
      data : $(this).serialize(), 
      success : function(data) { 
         alert('Submitted') 
         }, 
      error : function(xhr, err) { 
         alert(''Error);  
         } 
     });  
     return false; 
    }); 

代碼工作完美,沒有ajax。 但是,如果我通過ajax加載表單不起作用。我認爲這是因爲JavaScript加載後通過ajax加載表單。

任何解決方案?

+1

埃姆...去了解它是如何工作的?不,真的,如果你先用AjaxForm類將事件綁定到所有表單,然後用這個類加載另一個表單(無需綁定提交事件),它將不起作用(這真是奇怪:-)) – SergeS 2012-03-04 18:50:39

+4

@SergeS:對不起,我可以在評論框中對笑話進行投票。 – Student 2012-03-04 19:20:52

回答

30

如果使用jQuery 1.7+,您可以嘗試使用.on()委託事件並綁定到具有相同類的所有未來表單。 嘗試找到沒有動態插入的最接近的父代,而不是$(document)。

$(document).on('submit', 'form.AjaxForm', function() {    
     $.ajax({ 
      url  : $(this).attr('action'), 
      type : $(this).attr('method'), 
      dataType: 'json', 
      data : $(this).serialize(), 
      success : function(data) { 
         alert('Submitted'); 
      }, 
      error : function(xhr, err) { 
         alert('Error');  
      } 
     });  
     return false; 
    }); 
1

您不能附加處理直接到一個不存在的HTML

有2種方法來處理它。

將處理程序綁定到ajax的成功回調中。

$(formParentSelector).load(formFileUrl, function() { 
     /* within this success callback the new html exists and can run code*/ 
     AjaxForm(); 
    }); 

function AjaxForm(){ 
    jQuery('form.AjaxForm').submit(function() {    
     $.ajax({ 
      url  : $(this).attr('action'), 
      type : $(this).attr('method'), 
      dataType: 'json', 
      data : $(this).serialize(), 
      success : function(data) { 
         alert('Submitted'); 
         }, 
      error : function(xhr, err) { 
         alert('Error');  
         } 
     });  

              }) 
} 

另一種方式是將處理委託給文檔中的較高水平,因此對未來的匹配元素

avalibale
jQuery(document).on('submit','form.AjaxForm').submit(function() {    
     $.ajax({ 
      url  : $(this).attr('action'), 
      type : $(this).attr('method'), 
      dataType: 'json', 
      data : $(this).serialize(), 
      success : function(data) { 
         alert('Submitted'); 
         }, 
      error : function(xhr, err) { 
         alert('Error');  
         } 
     });  

              })