一 功能介绍
点击“评论”按钮时,不刷新页面,将评论内容直接插入下方的评论列表中。
二 实现方式
1. 为评论框表单设置id属性
// 为评论框表单设置id属性comment_form<form id="comment_form" action="{% url ‘update_comment‘ %}" method="POST" sytle="overflow:hidden"> ???{% csrf_token %} ???<label>{{ user.username }},欢迎评论</label> ???{% for field in comment_form %} ???????{{ field }} ???{% endfor %} ???// 添加错误提示框,并设置其id属性comment_error ???<span id="comment_error" class="text-danger pull-left"></span> ???<input type="submit" value="评论" class="btn btn-primary pull-right"></form>
2. 在{% url ‘update_comment‘ %}对应的方法中添加要返回到当前页面的数据
from django.shortcuts import render, redirectfrom django.contrib.contenttypes.models import ContentTypefrom django.urls import reversefrom django.http import JsonResponsefrom .models import Commentfrom .forms import CommentForm# Create your views here.def update_comment(request):referer = request.META.get(‘HTTP_REFERER‘,reverse(‘home‘))comment_form = CommentForm(request.POST, user=request.user)data = {}if comment_form.is_valid(): ???????????????# 要接收并保存的数据comment = Comment()comment.user = comment_form.cleaned_data[‘user‘]comment.comment_text = comment_form.cleaned_data[‘comment_text‘]comment.content_object = comment_form.cleaned_data[‘content_object‘]comment.save()# 要返回的返回数据# status 标记评论是否验证成功data[‘status‘] = ‘Success‘ ???????????????#评论列表中的单条评论格式如下: ???????????????#angryze (2018-11-27 15:00:37): ???????????????#444 ???????????????#因此返回的数据中需要三个要素: ???????????????#username 对应 angryze data[‘username‘] = comment.user.username ???????????????#comment_time 对应 (2018-11-27 15:00:37)data[‘comment_time‘]=comment.comment_time.strftime(‘%Y-%m-%d %H:%M:%S‘) ???????????????#text 对应 444data[‘text‘]=comment.comment_textelse:data[‘status‘] = ‘Error‘data[‘message‘] = list(comment_form.errors.values())[0][0] ???????// 以Json格式返回数据return JsonResponse(data) ???????????
3. 在模版页面中添加javascript语句
???????<script type="text/javascript">$("#comment_form").submit(function(){//第一步,判断是否为空$("#comment_error").text("");if(CKEDITOR.instances["id_comment_text"].document.getBody().getText().trim()==‘‘){$("#comment_error").text("评论内容不能为空");return false;}// 第二步,更新数据到textareaCKEDITOR.instances[‘id_comment_text‘].updateElement();// 第三步,设置ajax属性$.ajax({// 设置提交的url与<form>中的action相同url: "{% url ‘update_comment‘ %}",// 设置提交的方法是POSTtype: ‘POST‘,// 序列化表单中的值,其中$(this)表示当前函数的对象,此处代表comment_form表单data: $(this).serialize(),// 是否运用缓存?cache: false,// 提交成功,调用方法,返回json数据success: function(data){console.log(data);if(data[‘status‘]=="Success"){// 插入数据var comment_html = ‘<div>‘+ data[‘username‘] + ‘(‘ + data[‘comment_time‘] + ‘):‘ + data[‘text‘] + ‘</div>‘;$("#comment_list").prepend(comment_html);// 清空评论框的内容CKEDITOR.instances[‘id_comment_text‘].setData(‘‘);}else{// 如果提交提交不成功,在id=comment_error中返回错误信息$("#comment_error").text(data[‘message‘]);}},// 提交错误,调用方法error: function(xhr){console.log(xhr);}});}); ???????</script>
注明:学习资料来自“再敲一行代码的个人空间”以及“杨仕航的博客”
[Django学习]Django基础(15)_ajax的评论提交
原文地址:https://www.cnblogs.com/AngryZe/p/10022574.html