美文网首页
评论提交使用ajax提交实现

评论提交使用ajax提交实现

作者: brafei | 来源:发表于2018-08-14 16:33 被阅读0次

评论部分不刷新提交,用户体验感好。这里便使用ajax实现。

使用提交时,状态栏显示success,error

  1. 考虑到使用的是jQuery的ajax,首先便要导入jQuery库。本文使用的是jquery-1.12.4.min.js。
blog/base.html
 <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{% block title %}{% endblock %}</title>
   ** <script type="text/javascript" src="{% static 'jquery-1.12.4.min.js' %}"></script> **
    {% block header_extends %}{% endblock %}
</head>
  1. 之后我们便要实现异步这一功能,首先我们先给定form表单一个id值 form_comment,方便在js中使用
blog/blog_detail.html
<form **id="comment_form"** action="{% url 'update_comment' %}" method="POST" style="overflow:hidden">
  1. 创建ajax基本样式
blog/blog_detail.html
**
{% block script_extends %}
<script type="text/javascript">
    $("#comment_form").submit(function(){
    // 异步提交
    $.ajax({
        url: '{% url 'update_comment' %}', 
        type: 'POST',
        data: $(this).serialize(),
        cache: false,
        success: function(data){
            console.log(data); // 打印出来
            },
        error: function(xhr){
            console.log(xhr);
            }
        });
    return false; // 截止提交
    });
</script>
{% endblock %} **
  1. 处理返回数据(JSON样式)
comment/views.py
**
from django.http import JsonResponse
**

**
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.text = comment_form.cleaned_data['text']
        comment.content_object = comment_form.cleaned_data['content_object']
        comment.save()

        # 返回数据
        data['status'] = 'SUCCESS'

    else:
        data['status'] = 'ERROR'
        data['message'] = list(comment_form.errors.values())[0][0]
    return JsonResponse(data)
**
  1. 测试状态
    F12打开测试,点击console查看


    succeess or error 状态.PNG

加载返回数据

  1. 在update_comment中添加返回的数据
comment/views.py
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.text = comment_form.cleaned_data['text']
        comment.content_object = comment_form.cleaned_data['content_object']
        comment.save()
        **
        # 返回数据
        data['status'] = 'SUCCESS'
        data['username'] = comment.user.username
        data['comment_time'] = comment.comment_time.strftime('%Y-%m-%d %H:%M:%S')
        **  
  else:
        data['status'] = 'ERROR'
        data['message'] = list(comment_form.errors.values())[0][0]
    return JsonResponse(data)
  1. 测试


    加载数据.PNG

将数据插入到评论列表中

  1. 调制样式给评论列表一个id值 comment_list
blog/blog_detail.html
<div class="comment-area">
     <h3 class="comment-area-title">评论列表</h3>
           **
           <div id="comment_list">
               {% for comment in comments %}
                   <div>
                           {{ comment.user.username }}
                           ({{ comment.comment_time|date:"Y-m-d H:n:s" }}):
                           {{ comment.text }}
                       </div>
                   {% empty %}
                       暂无评论
                   {% endfor %}
       </div>
     **       
 </div>
  1. ajax中写入将后台JSON的数据加载到页面上
blog/blog_detail.html
{% block script_extends %}
<script type="text/javascript">
    $("#comment_form").submit(function(){
    // 异步提交
    $.ajax({
        url: '{% url 'update_comment' %}',
        type: 'POST',
        data: $(this).serialize(),
        cache: false,
        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);
            }
              **
            },
        error: function(xhr){
            console.log(xhr);
            }
        });
    return false; // 截止提交
    });
</script>
{% endblock %}
  1. 测试


    加载返回的数据.PNG

附上最终完整代码,其中包含评论部分的ckeditor编辑

blog/blog_detail.html
{% block script_extends %}
<script type="text/javascript">
    $("#comment_form").submit(function(){
    // 异步提交
    $.ajax({
        url: '{% url 'update_comment' %}',
        type: 'POST',
        data: $(this).serialize(),
        cache: false,
        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);
            }
            },
        error: function(xhr){
            console.log(xhr);
            }
        });
    return false; // 截止提交
    });
</script>
{% endblock %}

相关文章

网友评论

      本文标题:评论提交使用ajax提交实现

      本文链接:https://www.haomeiwen.com/subject/hosamftx.html