在試了很多次了,終於搞定了,上代碼吧。(我用的是jQuery的ajax,不是原生的)
js代碼:
<script> $(document).ready(function () { getcomment(); $('.comment-box button').click(function () { var comment_text = $('.comment-box textarea').val(); $.ajax({ type: 'POST', url: '/bbs/article/{{ article_list.id }}/comment/', data: {comment: comment_text}, success:function (callback) { var data = $.parseJSON(callback); $('.callback').html(data.result); if(data.result === 'successfully') { getcomment(); } } }) }); }); function getcomment() { $.ajax({ type: 'GET', url: '/bbs/article/{{ article_list.id }}/get_comment/', success:function (call) { var datas = $.parseJSON(call); $('.comment-list').html(datas.answer); } }) } </script>
在全文加載後調用getcomment()函數,從數據庫中獲取評論,自己寫的評論提交後再次調用getcomment()函數,自動刷新
html模板(用到是bootstrap模板):
<div class="row"> <div class="comment-list" style="margin-left: 10px"> </div> </div> <div class="row"> <article class="col-xs-12"> <h4>請評論:</h4> <div class="comment-box"> <textarea class="form-control" rows="3"></textarea> <span class="callback"></span><button type="submit" class="btn btn-success pull-right" style="max-width: 5px;">評論</button> </div> </article> </div> <hr>
視圖函數:
@csrf_exempt def comment(request,article_id): if request.method == 'POST': comments = request.POST['comment'] if len(comments) < 5: result = u'評論數需大於5' return HttpResponse(json.dumps({'result': result})) else: result = 'successfully' Comment.objects.create(content= comments, article_id=article_id) return HttpResponse(json.dumps({'result': result}))
這是提交評論的函數,別忘記添加csrf裝飾器
def get_comment(request, article_id): article_list = get_object_or_404(Article, id=article_id) comments = article_list.comment_set.all() html = '' for i in comments: ele = '<div class="row"><article class="col-xs-12"><p class="pull-right"><span class="label label-default">作者:' + 'i.user' + '</span></p><p>' + i.content + '<ul class="list-inline"><li><a href="#" rel="external nofollow" ></a></li></ul></article></div><hr>' html += ele return HttpResponse(json.dumps({'answer': html}))
後台獲取評論的函數。
最後將textarea的值清空:
function resettext() { $('.form-control').val(''); }
以上所述是小編給大家介紹的django ajax提交評論並自動刷新功能的實現代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對網站的支持!