【发布时间】:2017-06-19 10:08:01
【问题描述】:
我有一个Comment 模型,它有 2 个视图:1 个用于家长评论,1 个用于回复。父视图工作正常,但由于某种原因,我的回复视图被调用了两次,这一次创建了 2 个回复对象。所以首先这里有一个.reply 按钮,用户单击它会调出评论表单并为该评论表单提供onclick 值reply_comment():
$('.reply').on('click', function(e) {
var clone = $('.comment_form').clone();
parent_id = $(this).closest('.comment_div').data('comment_id');
$(this).closest('.comment_div').after(
clone
);
clone.addClass('reply_comment_form').removeClass('comment_form');
clone.attr('onclick', 'reply_comment()');
clone.data('comment_id', parent_id);
$(this).next().css('display', 'inline-block');
$(this).css('display', 'none');
$('.reply_comment_form').css('padding', '1px');
});
这是实际的功能:
function reply_comment() {
$('.reply_comment_form').on('submit', function (e) {
e.preventDefault();
parent_id = $('.reply_comment_form').data('comment_id');
$.ajax({
type: 'POST',
url: '/comment_reply/',
data: {
reply_text: $(this).find('.comment_text').val(),
parent_id: parent_id,
id: path,
csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val(),
},
success: function(data) {
$('.reply_comment_form').replaceWith("<div class='comment_div new_comment'><div class='left_comment_div'>" +
"<div class='username_and_votes'><h3><a href='#' class='username'>" + data.username +
"</a></h3><span class='upvotes' style='margin: 0 6'>0</span><span class='downvotes'>0</span></div><br><p>" + data.reply_text +
"</p></div><a href='#'><span class='comment_delete'>x</span></a></div>");
$('.new_comment').css({
'width': '72%',
'margin': '0 70 10 0',
'float': 'right',
});
$('.new_comment').next().css('clear', 'both');
$('.new_comment').prev().find('.cancel_comment').css('display', 'inline-block')
.find('.cancel_comment').css('display', 'inline-block');
}
});
});
}
此 AJAX 调用成功附加回复,并发送到此视图以将其保存到数据库:
def comment_reply(request):
print('reply')
if request.is_ajax():
comment = CommentForm(request.POST or None)
reply_text = request.POST.get('reply_text')
id = request.POST.get('id')
parent_id = request.POST.get('parent_id')
parent = Comment.objects.get(id=parent_id)
if comment.is_valid():
comment = Comment.objects.create(comment_text=reply_text, destination=id, user=request.user, parent_id=parent_id, parent_comment=parent)
username = str(request.user)
return JsonResponse({'reply_text': reply_text, 'username': username})
一切正常,除了这个视图被调用两次并创建了 2 个Comment 对象。知道为什么会这样吗?
【问题讨论】:
-
代码看起来过于复杂。我认为您根本不需要将
onsubmit包装到reply_comment()函数中。我认为你那里的onclick可以执行多次,然后onsubmit的东西也被绑定两次。 -
我自己尝试了
$('.reply_comment_form').on('submit', function {,但没有被调用。进行 onsubmit 思考是我唯一的选择。 -
当然可以,因为在创建文档时该元素并不存在。尝试这样的事情:
$(document).on('submit', '.reply_comment_form', function(e) { ... -
这工作非常感谢你。你的代码与
$('.reply_comment_form').on('submit', function {有什么不同?
标签: jquery ajax django django-views