2015-10-12 27 views
0

我嘗試使用Ajax和jquery表單驗證發佈數據,但是它在第一次提交驗證功能時不起作用。任何方案?Ajax表單發佈和驗證不起作用

$(document).ready(function() { 
$("#myForm").validate(); 
}); 

(function($){ 
    function processForm(e){ 
     $.ajax({ 
      url: 'post.php', 
      dataType: 'text', 
      type: 'post', 
      contentType: 'application/x-www-form-urlencoded', 
      data: $(this).serialize(), 
      success: function(data, textStatus, jQxhr){ 
       //$('#response pre').html(data); 
       alert('scuss'); 
      }, 
      error: function(jqXhr, textStatus, errorThrown){ 
       //console.log(errorThrown); 
       alert('error'); 
      } 
     }); 

      e.preventDefault(); 
    } 

$('#myForm').submit(function(e){ 
e.preventDefault(); 
if(!$("#myForm").valid()) return; 
$('#myForm').submit(processForm); 
}); 
})(jQuery); 

回答

1

你爲什麼打電話submit裏面submit?只需調用在else部分function processForm如下:

$('#myForm').submit(function(e){ 
    e.preventDefault(); 
    if(!$(this).valid()) 
     return; 
    else 
     processForm($(this)); 
}); 

無需通過e充當你已經默認阻止的formaction,而不是通過form本身。

function processForm(form){ 
    var $this=$(form);//cache the form 
    $.ajax({ 
      url: 'post.php', 
      dataType: 'text', 
      type: 'post', 
      contentType: 'application/x-www-form-urlencoded', 
      data: $this.serialize(), 
      success: function(data, textStatus, jQxhr){ 
       //$('#response pre').html(data); 
       alert('scuss'); 
      }, 
      error: function(jqXhr, textStatus, errorThrown){ 
       //console.log(errorThrown); 
       alert('error'); 
      } 
     }); 
}