javascript - AJAX 在数据库中输入数据两次

标签 javascript jquery ajax

我有一个功能,用户可以举报帖子,用户单击举报按钮,然后立即输入举报信息。这是可行的,问题是如果页面尚未重新加载并且用户决定报告第二篇文章,则该报告的数据会进入数据库两次。这是为什么?

代码如下:

$(document).ready(function() {
  $(".report_post").click(function(e) {
    var nid = $(this).attr("id");
    $("#report_reason").dialog({
      resizable: false,
      height: 300,
      width: 400,
      modal: true,
    });

    $('.submit_report_post').click(function() {
      var content = $("#report_content").val();
      var type = "Post";
      if ($('input[name="report"]:checked').length > 0 && (content != null &&
        content != "")) {
        var complaint = document.querySelector('input[name="report"]:checked').value;
        alert('Reported!');
        $.ajax({
          type: 'POST',
          url: 'php/report_post.php',
          data: {
            type: type,
            nid: nid,
            reason: complaint,
            content: content,
          },
          cache: false,
          success: function(data) {
            $("#report_content").val("");
            $("input[name='report']").prop('checked', false);
            //$("#report_reason").dialog('close');
          }
        });
      } else {
        alert('Fill all of the information!');
      }
    });
    e.preventDefault();
  });
});

最佳答案

您将提交表单两次,一次通过正常方式提交,一次通过 AJAX 提交。您的代码中有 e.preventDefault();,通常会停止典型的非 AJAX 提交,但您从未创建 e 参数。

更改:

$('.submit_report_post').click(function() {

$('.submit_report_post').click(function(e) {

这将使表单仅通过 AJAX 代码提交。

关于javascript - AJAX 在数据库中输入数据两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41144634/

相关文章:

javascript - 查找两个字符串正则表达式中常见出现的单词

javascript - 如何使用 Ember 将动态段的值输出到页面上?

javascript - 将 JQuery 函数应用于自定义类类型?

javascript - jQuery 滚动 DIV 跳动且定位不正确

javascript - 带 for 循环的 AJAX Done() 函数

javascript - 使用 IF 语句更新 mysql 查询

javascript - 使用变量创建 json 对象

javascript - 克隆换行时如何防止字溢出?

javascript - Nodejs通过回调方法发送ajax给客户端

jquery - 如何从 ajax 返回的 HTML 访问 json 数据?