2016-08-17 86 views
0

我想通过ajax-jquery提交一个子窗体,内部父窗体,以便它不刷新整个页面。代码是:通过ajax提交嵌套表单提交子表单,但没有页面刷新

<!doctype html> 
    <html> 
    <head> 
    <meta charset="utf-8"> 
    <title>Untitled Document</title> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> 
    <script type="text/javascript"> 
    $(document).ready(function (e) { 
     $(document).on('submit', '#form-2', function() { 
      var data = $(this).serialize(); 
      $.ajax({ 
       type : 'POST', 
       url : 'a2.php', 
       data : data, 
       success : function(data) {      
        $("#form-2").fadeOut(500).hide(function() { 
         $(".result").fadeIn(500).show(function() { 
          $(".result").html(data); 
         }); 
        }); 

       } 
     }); 

     return false; 
    }); 

    }) // document ready ends here; 
    </script> 
    </head> 
    <body> 
    <form action="a1.php" method="post" name="form-1" id="form-1"> 
     <input type="text" name="f1" /> 
     <input type="text" name="f2" /> 
     <input type="text" name="f3" /> 
     <input type="text" name="f4" /> 
     <!-----form 2 ajax starts-----> 
     <form method="post" name="form-2" id="form-2"> 
      <input type="text" name="g1" /> 
      <input type="submit" id="sf2"> 
     </form><!-----form-2 ends-----> 
    </form><!-----form-1 ends-----> 
    </body> 
    </html> 

但它没有工作,它根本就没有。我也用过 - preventdefault() 有什么帮助吗?我试图简单地在数据库中提交表单2值,从表单-1的一些下拉列表中获取所有选项值。

+1

不允许嵌套表格。 –

+0

http://stackoverflow.com/questions/379610/can-you-nest-html-forms – Typoheads

+1

不能嵌套窗体我的朋友。 – ThatAwesomeCoder

回答

0

你可以使用:

$(document).on('click', '#sf2', function(event) { 
    var g1 = $('#g1').val(); 
    $.ajax({ 
     type : 'POST', 
     url : 'a2.php', 
     data : { 
      g1: g1 
     }, 
     success : function(data) { 
      $("#form-2").fadeOut(500).hide(function() { 
       $(".result").fadeIn(500).show(function() { 
        $(".result").html(data); 
       }); 
      }); 

     } 
    }); 
}); 

,并使用一个普通按钮:

<input type="text" name="g1" id="g1" /> 
<button type="button" id="sf2">Submit</button> 

这是不好的作风虽然为形式不应该被嵌套。