Django ajax submits comments and automatically refreshes the implementation code of the function. django submits comments.
I tried it many times and finally got it done. Let's go to the code. (I am using jQuery ajax, not native)
Js Code:
<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>
Call the getcomment () function after loading the full text to obtain comments from the database. Call the getcomment () function again after you submit your own comments to automatically refresh the page.
Html template (bootstrap template used ):
<Div class = "row"> <div class = "comment-list" style = "margin-left: 10px "> </div> <div class =" row "> <article class =" col-xs-12 ">
View functions:
@ Csrf_exemptdef comment (request, article_id): if request. method = 'post': comments = request. POST ['comment'] if len (comments) <5: result = U' the number of comments must be greater than 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 }))
This is a function for submitting comments. Do not forget to add the csrf modifier.
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-default"> author: '+' I. user '+' </span> </p> <p> '+ I. content + '<ul class = "list-inline"> <li> <a href = "#" rel = "external nofollow"> </a> </li> </ ul> </article> </div>
Function used to obtain comments in the background.
Finally, clear the textarea value:
function resettext() { $('.form-control').val('');}
The above is the implementation code of the django ajax function submitted by the editor and automatically refreshed. I hope it will be helpful to you. If you have any questions, please leave a message for me, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!