javascript - 如何使用 JQuery 和 PHP 为多个表单设置唯一 id

标签 javascript php jquery ajax

我的页面中有超过 1 个表单。我使用ajax 将此表单提交到数据库。问题是每个表单都应该有唯一的 id 才能使用 ajax(JQuery id 选择器)提交,并且第一个表单总是使用 ajax 提交,其他表单总是使用 php 提交。我如何为每个表单提供唯一的 id 并使用 AJAX 提交所有表单?

<form action="inc/new.comment.php" method="post" id="new_comment_answer_form">
    <textarea name="new_answer" id="new_answer" cols="30" rows="10" placeholder="enter your new answer"></textarea>
    <!-- <input type="text" name="comment_author" id="comment_author" placeholder="author name"> -->
    <input type="hidden" name="post_id" id="post_id" value="<?php echo $post_id ?>">
    <input type="hidden" name="comment_id" id="comment_id" value="<?php echo $comment_id ?>">
    <input type="submit" name="submit_answer" value="send" id="submit_answer">
</form>
<p id="new_answer_result"></p>

j查询:

 $("#new_comment_answer_form").submit(function (e) {
        e.preventDefault();
        var new_answer = $("#new_answer").val();
        var submit_answer = $("#submit_answer").val();
        var post_id = $("#post_id").val();
        var comment_id = $("#comment_id").val();
        $(document).ajaxStart(function () {});
        $(document).ajaxComplete(function () {});
        $.post("./inc/new.comment.php", {
            new_answer: new_answer,
            submit_answer: submit_answer,
            post_id: post_id,
            comment_id: comment_id
        }, function (data, status) {
            $("#new_answer_result").html(data);
            $("#new_answer").val("");
        });
    });

使用此代码是对博客网站中其他评论的评论。(如果有帮助的话)

最佳答案

您可以为每个表单提供唯一的 ID,但设置相同的类,例如 class="submit_form"。接下来您应该通过此类调用该函数。您可以通过名称调用其他字段。

$(".submit_class").submit(function (e) {
    e.preventDefault();
    var new_answer = $(this).find("[name=new_answer]").val();
    var submit_answer = $(this).find("[name=submit_answer]").val();
    var post_id = $(this).find("[name=post_id]").val();
    var comment_id = $(this).find("[name=comment_id]").val();
    $(document).ajaxStart(function () {});
    $(document).ajaxComplete(function () {});
    $.post("./inc/new.comment.php", {
        new_answer: new_answer,
        submit_answer: submit_answer,
        post_id: post_id,
        comment_id: comment_id
    }, function (data, status) {
        $("#new_answer_result").html(data);
        $(this).find("[name=new_answer]").val("");
    });
});

关于javascript - 如何使用 JQuery 和 PHP 为多个表单设置唯一 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50894088/

相关文章:

javascript - 扩展篮子 js 功能以动态加载脚本

php - 我如何更新 php 数据库中已有的记录

php - 使用 JQuery 或 Javascript 刷新图像

php - 如何将图像上传添加到 WordPress 选项面板

javascript - 检查元素是否具有特定的类和特定的 ID

javascript - 如何使用数据库中的图像动态更新 HTML 中的图像

javascript - 想要使用 javascript/jquery 在输入标记中显示文件上传大小

javascript - Javascript中对象过滤的突变问题

php - 如何将 "AddThis"按钮添加到 Joomla

php - "Something is wrong with the XAMPP installation :-("是什么意思?