如何解决Ajax成功功能不起作用:Django JSONResponse无法发送
在下面的代码中,我使用onclick(我知道这可能不是最佳实践,但对于我的特殊情况,我认为它最有效)来激活ajax调用,以动态更新Django模板上的内容。到目前为止,数据将流向后端,并且正在创建Comment对象。
但是,当返回JSONResponse时,模板未使用此JSONResponse中的数据以任何方式更新页面。我已经尝试过对警报进行测试,但无济于事。我是JS的新手,所以我希望提供一些帮助!非常感谢。
Django视图:
def sochome(request,oid):
society = Society.objects.filter(id=oid).first()
membership = SocietyMembership.objects.get(member=request.user,society=society)
response_data = {}
if request.method == 'POST':
postID = request.POST.get('post_id')
comment_content = request.POST.get('comment')
response_data['post_id'] = postID
response_data['comment'] = comment_content
post = SocPost.objects.filter(id=postID).first()
SocComment.objects.create(post=post,author=request.user,content=comment_content)
# print(response_data,file=sys.stderr)
# print("SUCCESS JSON RESPONSE TO CLIENT SIDE",file=sys.stderr)
return JsonResponse(response_data)
context = {
'membership': membership,'posts': society.posts.all().order_by('-date_posted')
}
return render(request,'blog/sochome.html',context)
HTML:
< script type = "text/javascript" >
function update_comment(post_id) {
$.ajax({
type: 'POST',url: "{% url 'blog-sochome' oid=membership.society.id%}",data: {
'post_id': post_id,'comment': document.getElementById(post_id.toString()).value
},dataType: 'text',success: function(data) {
alert("ajax completed ");
}
});
} <
/script>
<div id="{{post.id}}-comment-section" class="mb-3 pr-5 pt-4 pb-2 bg-light shadow-sm border-light" style="border-bottom-left-radius: 0.5rem; border-bottom-right-radius: 0.5rem;">
<div class="col-sm-12 pl-5 pb-5">
<form class="form-inline" method="POST" action="" style="display:flex" id="comment"> {% csrf_token %}
<input id="{{post.id}}" type="search" name="comment" placeholder="New comment" class="form-control mr-sm-2 p-4" style="flex-grow:1;">
<button name="post_id" class="btn btn-info my-2 my-sm-0 " value="{{post.id}}" onclick="update_comment({{post.id}})"> Post </button>
</form>
</div>
{% for comment in post.comments.all %}
<div class="row">
<div class="col-xs-1 offset-1 pl-4">
<img class="rounded-circle comment-image" src="{{ comment.author.profile.image.url }}" />
</div>
<div class="col-xs-4">
<a class="mr-2 comment-author-name" href="#">{{ comment.author.first_name }} {{ comment.author.last_name }}</a>
<small class="text-muted comment-time"><br>{{ comment.date_posted|date:"F d,Y" }}</small>
</div>
</div>
<div class="row">
<div class="col-sm-12 offset-1">
<p class="comment-content">{{ comment.content }}</p>
</div>
</div>
{% empty %}
<div class="px-5">
<p>No comments for this post.</p>
</div>
{% endfor %}
</div>
{% endfor %}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。