jquery提交表单不起作用

时间:2014-08-30 07:53:10

标签: jquery

我想用jquery提交一个表单,但它没有工作,我尝试调试但发现它甚至没有进入提交方法。无法弄清楚为什么

 $("#btn").click(function(){
      $('form').submit(function(event){
         alert('11');
         event.preventDefault();
         $.post("${contextPath}/announcement/addAnnoPubToPerson.action",$(this).serialize()).done(alert('done'));
        });
    });

我也试过

   $("#btn").click(function(){
      $(document).on('submit','form',function(event){
         alert('11');
         event.preventDefault();
         $.post("${contextPath}/announcement/addAnnoPubToPerson.action",$(this).serialize()).done(alert('done'));
        });
    });

仍然无法正常工作。

3 个答案:

答案 0 :(得分:2)

你的btn点击处理程序都会将一个监听器附加到表单提交而不是其他内容。单击该按钮将不会提交表单。如果按钮触发了普通表单提交,则可以完全忽略单击处理程序,以下内容应该可以正常工作:

$('form').submit(function(event){
     alert('11');
     event.preventDefault();
     $.post("${contextPath}/announcement/addAnnoPubToPerson.action",$(this).serialize()).done(alert('done'));
  });

如果按钮没有触发普通表单提交,请使用@Exception的答案。

值得注意的是,$('表单')。submit()将侦听所有表单提交,您可能希望通过为目标表单提供类来阻止对其他表单的提交处理或标识符,并使用以下代码:

$('form.THEFORM').submit(...)

答案 1 :(得分:1)

试试这个:

 $("#btn").click(function(){
   $("form").trigger('submit');
 });

  $('form').submit(function(event){
     alert('11');
     event.preventDefault();
     $.post("${contextPath}/announcement/addAnnoPubToPerson.action",$(this).serialize()).done(alert('done'));
  });

如果你的#btn不是输入类型提交,上面的答案很有用,如果它的输入类型是提交的,那么只有下面的代码才有效:

$('form').submit(function(event){
     alert('11');
     event.preventDefault();
     $.post("${contextPath}/announcement/addAnnoPubToPerson.action",$(this).serialize()).done(alert('done'));
  });

您的案例中的问题是因为'点击'并提交'是两个不同的jquery事件,'提交'当您按下输入类型提交按钮时,事件会自动触发表单。

答案 2 :(得分:0)

使用AJAX代替:

$('.success-message').hide();
$('.error-message').hide();

$('.get form').submit(function(e) {
    e.preventDefault();
    var postdata = $('.get form').serialize();
    $.ajax({
        type: 'POST',
        url: 'assets/submit.php',
        data: postdata,
        dataType: 'json',
        success: function(json) {
            if(json.valid == 0) {
                $('.success-message').hide();
                $('.error-message').hide();
                $('.error-message').html(json.message);
                $('.error-message').fadeIn();
            }
            else {
                $('.error-message').hide();
                $('.success-message').hide();
                $('.get form').hide();
                $('.success-message').html(json.message);
                $('.success-message').fadeIn();
            }
        }
    });
});
相关问题