繁体   English   中英

通过ajax提交以嵌套形式提交子表单,无需页面刷新

[英]Submit child-form in Nested-forms via ajax submit, without page-refresh

我正在尝试通过ajax-jquery提交父表单内的子表单,以便不刷新整个页面。 代码是:

    <!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()有帮助吗? 我正在尝试简单地在数据库中提交form-2值,从form-1的某些下拉列表中获取所有选项值。

您可以使用:

$(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>

这不是一个好的样式,尽管不应嵌套表格。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM