同一页面上的多个表单AJAX

Multiple Forms on Same page AJAX

本文关键字:表单 AJAX 一页      更新时间:2023-09-26

我在完成这项工作时遇到了麻烦。我需要在同一页上有多个表格。。。我试过无数种方法,但似乎都无效。

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

这是我当前的代码

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必须是唯一的,所以你可以使用一个类,但你真的根本不需要任何标识符,也不需要数据属性,.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元素上使用一个类来根据表单查找它。