码迷,mamicode.com
首页 > Web开发 > 详细

[Django学习]Django基础(15)_ajax的评论提交

时间:2019-01-18 22:27:29      阅读:253      评论:0      收藏:0      [点我收藏+]

标签:pre   div   ever   target   介绍   btn   模版   def   ane   

一 功能介绍

  点击“评论”按钮时,不刷新页面,将评论内容直接插入下方的评论列表中。

  技术分享图片

二 实现方式

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, redirect
from django.contrib.contenttypes.models import ContentType
from django.urls import reverse
from django.http import JsonResponse
from .models import Comment
from .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 对应 444
		data[‘text‘]=comment.comment_text
	else:
		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;
			}

			// 第二步,更新数据到textarea
			CKEDITOR.instances[‘id_comment_text‘].updateElement();
			// 第三步,设置ajax属性
			$.ajax({
				// 设置提交的url与<form>中的action相同
				url: "{% url ‘update_comment‘ %}",
				// 设置提交的方法是POST
				type: ‘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的评论提交

标签:pre   div   ever   target   介绍   btn   模版   def   ane   

原文地址:https://www.cnblogs.com/AngryZe/p/10022574.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!