gpt4 book ai didi

Django ajax 使用 Jquery 注释?

转载 作者:行者123 更新时间:2023-12-01 02:48:27 26 4
gpt4 key购买 nike

我想实现一个ajax评论系统。

url.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,{'comments': comments,'feed': feed,'form':form,})
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>

我应该包含什么代码来将评论添加到评论列表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);
});
});

关于Django ajax 使用 Jquery 注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6158452/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com