2016-12-27 192 views
1

当创建一个jQuery函数来提交表单时,我需要在发送请求之前首先进行验证。这里是我的代码:jQuery表单提交验证

$('#Form').submit(function(e){ 
    e.preventDefault(); 
    e.stopImmediatePropagation(); 
    var PhotoID = $('#PhotoID').val(); 
    // I will set the PhotoID to 0 just for testing. 
    var PhotoID = '0'; 
    if (PhotoID == '0') { 
     $('#GlobalError').removeClass('hidden'); 
    } else { 
     return true; 
     $.ajax({ 
      type: "POST", 
      url: $(this).attr('action'), 
      data: $(this).serialize(), 
      beforeSend: function(){ 
       $("#loader").fadeIn(2000); 
      }, 
      success: function(response) { 
      } 
     }); 
    } 
}); 

PhotoID0不同,我想提交表单,并按照正常的页面转变,形成action属性。我知道e.preventDefault()的反义词是return true;,但不起作用。该功能正在被正确触发。所以问题就在于表单提交处理。

回答

1

使用return false避免表单提交

$('#Form').submit(function(e){ 
    var PhotoID = $('#PhotoID').val(); 
    // I will set the PhotoID to 0 just for testing. 
    var PhotoID = '0'; 
    if (PhotoID == '0') { 
     $('#GlobalError').removeClass('hidden'); 
     return false; 

    } else { 

     $.ajax({ 
      type: "POST", 
      url: $(this).attr('action'), 
      data: $(this).serialize(), 
      beforeSend: function(){ 
       $("#loader").fadeIn(2000); 
      }, 
      success: function(response) { 
      } 
     }); 
    } 
}); 

但它从来没有提交,因为你设置PhotoID值为0

+1

它的工作。我标记这只是为了更好地理解代码。我将在未来为有相同问题的人更正代码。谢谢 – rgomez