问题描述
|
我想实现一个ajax评论系统。
urls.py:
(r\'^comment/(\\d+)/$\',comments),
views.py:
def comments(request,Feed):
if request.method == \'POST\':
Feed=Feed.objects.get(pk=Feed)
form = CommentForm(request.POST)
if form.is_valid():
comment,created = Comment.objects.get_or_create(
Feed=Feed,msg=form.cleaned_data[\'msg\'],ip=request.Meta[\'REMOTE_ADDR\']
)
comments=Comment.objects.filter(Feed=Feed)
form=CommentForm()
variables=RequestContext(request,{\'comments\': comments,\'Feed\': Feed,\'form\':form,})
if \'HTTP_REFERER\' in request.Meta:
return HttpResponseRedirect(request.Meta[\'HTTP_REFERER\'])
return render_to_response(\'comment_page.html\',variables )
#return HttpResponseRedirect(\'/view/\')
else:
form=CommentForm()
Feed=Feed.objects.get(pk=Feed)
comments=Comment.objects.filter(Feed=Feed).reverse()
variables=RequestContext(request,})
return render_to_response(\'comment_page.html\',variables )
范本:
<div id=\"commentBox\" style=\"display:none;\">
<form class=\"comment\" method=\"post\" action=\"/comment/{{Feed.id}}/\">
{{cform.as_p}}
<input class=\"post\" type=\"submit\" value=\"post\" />
</form>
</div>
</br>
<h3></h3><button class=\"ccc\">Show/Hide Comment</button> {{Feed.comment_set.count}} Comments
<div id=\"commentlist\" class=\"commentlist\" style=\"padding-left:10px;\"><ul style=\"list-style-type:square;\">
{% for c in Feed.comment_set.all %}
<li>{{c.msg}}</li>
{% endfor %}
</ul>
</div>
我应该包括什么代码才能在不刷新页面的情况下将评论添加到commentlist li字段中。我是ajax的新手。请帮忙。谢谢
解决方法
这是我要做的:
保留HTML不变,因为它适用于没有JavaScript的人。在您的JavaScript中,当用户提交表单时,阻止它实际发生:
$(\'#commentbox form\').submit(function(e) {
e.preventDefault();
});
现在,当按下按钮时,阻止默认行为并通过AJAX提交表单:
$(\'#commentbox form\').submit(function(e) {
e.preventDefault();
$.ajax({
type: \'post\',url: $(this).parent().attr(\'action\'),data: $(this).parent().serialize(),}).done(function(data) {
alert(\'The AJAX is done,and the server said \' + data);
});
});