动态指定输出多个表单的ajax成功结果的位置

时间:2015-02-08 21:46:15

标签: javascript php jquery html ajax

我有两个问题:

  1. 如何在同一页面中创建第二个表单,并根据单击的提交按钮,ajax处理正确的表单?

  2. 现在假设我在同一页面中有多个表单。我想根据点击的提交按钮更改输出的位置。

  3. 源代码:

    的Ajax:

    <script type="text/javascript">
        $(document).ready(function(){
            $("#myform").validate({
                submitHandler: function(form) {
                    // do other stuff for a valid form
                    $.post('post.php', $("#myform").serialize(), function(data) {
                        $('#results').html(data);
                    });
                }
            });
        });
    </script>
    

    HTML

    <form id="myform" action="" method="POST">
        <input type="text" name="a"><input type="submit" value="submit">
    </form>
    <div id="results"></div> <!-- post.php output goes here.-->
    <!-- until here everything is working fine -->
    <!-- now if I want to add a second form I don't know what id I should use -->
    

1 个答案:

答案 0 :(得分:0)

我会在你的表单上使用一个类来绑定,然后每个表单都可以有一个元素来保存你选择的输出id -

的javascript

<script type="text/javascript">
    $(document).ready(function(){
        $(".myforms").validate({
            submitHandler: function(form) {
                // do other stuff for a valid form
                $.post('post.php', $(form).serialize(), function(data) {
                    var output = $(form).data('output');
                    $("#"+output).html(data);
                });
            }
        });
    });
</script>

HTML

<form class="myforms" action="" method="POST" data-output="results1">
    <input type="text" name="a"><input type="submit" value="submit">
</form>
<div id="results1"></div>    

<form class="myforms" action="" method="POST" data-output="results2">
    <input type="text" name="a"><input type="submit" value="submit">
</form>
<div id="results2"></div>  

<form class="myforms" action="" method="POST" data-output="results3">
    <input type="text" name="a"><input type="submit" value="submit">
</form>
<div id="results3"></div>