同一页上的多个表单 AJAX

Multiple Forms on Same page AJAX

我在完成这项工作时遇到了麻烦。 我需要在同一页面上有多个表单...我尝试了无数种方法,但似乎没有任何效果。

我在这里要做的是(以某种方式)识别每个表单,以便提交该表单而不是页面上的第一个表单。下面的代码有效,但始终提交相同的表单,第一个!

这是我当前的代码

JS:

$(document).ready(function(){

    $('.submit').on("click", function() {

        var artworkId = $("#inquirebox").data("artworkid");

        $.post("send.php";, $("#artinquire"+artworkId).serialize(), function(response) {
            $('#success').html(response);
        });

        return false;

    });

});

HTML:

<div id="inquirebox" data-artworkid="<?php echo 456;?>">
    <form action="" method="post" id="artinquire<?php echo 456;?>" data-artworkid="<?php echo 456;?>">
        <label for="name">Name:</label><br />
        <input type="text" name="name" id="name" /><br />

        <label for="email">Email:</label><br />
        <input type="text" name="email" id="email" /><br />

        <label for="message">Message:</label><br />
        <textarea name="message" id="message"></textarea><br />

        <input type="hidden" name="id" value="<?php echo 456;?>">
        <input type="hidden" name="artist" value="<?php echo $title1; ?>">
        <input type="hidden" name="url" value="<?php echo $uri1; ?>">
        <input type="hidden" name="artwork" value="<?php echo $artwork1; ?>">

        <input type="button" value="send" class="submit" id="submit" data-artworkid="<?php echo 456;?>">
        <div id="success"></div>
    </form>
</div>

您在表单的所有 DIV 包装器上使用相同的 ID。

ID 必须是唯一的,因此您可以使用 class 代替,但您实际上根本不需要任何标识符,也不需要数据属性,.submit 按钮在里面表单,所以您只需要 this.form,或更多 jQuery'ish $(this).closest('form') 来获取父表单

$(document).ready(function(){

    $('.submit').on("click", function() {

        var form = $(this).closest('form');

        $.post("send.php", form.serialize(), function(response) {
            form.find('.success').html(response);
        });

        return false;

    });
});

然而,您应该在 #success 元素上使用 class 以根据表单找到它。