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