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

时间:2016-12-14 14:07:30

标签: javascript jquery ajax

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

以下是代码:

g = df.groupby('A').B
df['B_max'] = g.transform(max)
df['B_min'] = g.transform(min)

print (df)
    A  B  C  B_max  B_min
0   1  5  1      7      5
1   1  7  1      7      5
2   1  6  1      7      5
3   1  7  1      7      5
4   2  5  1      8      5
5   2  8  1      8      5
6   2  6  1      8      5
7   3  7  1      9      7
8   3  9  1      9      7
9   4  6  1      7      1
10  4  7  1      7      1
11  4  1  1      7      1

2 个答案:

答案 0 :(得分:2)

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

变化:

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

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

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

答案 1 :(得分:0)

每次点击click时,您都会$('.submit_report_post')绑定$(".report_post"),您需要在第一次绑定之外执行此操作

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

  $('.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!');
    }
  });

});