How to use ajax to submit comments and automatically refresh them

php中世界最好的语言
Release: 2018-03-31 15:29:36
Original
2746 people have browsed it

This time I will show you how to use ajax to submit comments and automatically refresh them. What are theprecautionsfor using ajax to submit comments and automatically refresh them. The following is a practical case, let's take a look.

After trying many times, I finally got it, let’s code it. (I use jQuery's ajax, not native)

js code:

Copy after login

Call the getcomment() function after the full text is loaded, get the comments from the database, and submit the comments written by yourself Then call the getcomment() function again to automatically refresh the

html template (thebootstraptemplate is used):

请评论:


Copy after login

View function:

@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}))
Copy after login

This It is the function to submit comments. Don’t forget to add the csrf decorator

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 = '

作者:' + 'i.user' + '

' + i.content + '


' html += ele return HttpResponse(json.dumps({'answer': html}))
Copy after login

The function to get comments in the background.

Finally clear the value of textarea:

function resettext() { $('.form-control').val(''); }
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

Detailed tutorial on making a shopping cart with Ajax+PHP

How to implement AJAX paging effect

The above is the detailed content of How to use ajax to submit comments and automatically refresh them. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!