2016-08-17 83 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> 

這是不好的作風雖然爲形式不應該被嵌套。