显示评论而不刷新

时间:2017-05-01 19:55:49

标签: javascript jquery ajax django

我想在发布后立即显示评论用户帖子。我已经将ajax上传了评论,如何将其显示给用户,而不刷新?我有这个ajax代码:

  $(".comments input[name='post']").keydown(function (evt) {
    var keyCode = evt.which?evt.which:evt.keyCode;
    if (keyCode == 13) {
      var form = $(this).closest("form");
      var container = $(this).closest(".comments");
      var input = $(this);
      $.ajax({
        url: "{% url 'comment' letnik_id=letnik_id classes_id=classes_id subject_id=subject_id %}",
        data: $(form).serialize(),
        type: 'post',
        cache: false,
        beforeSend: function () {
          $(input).val("");
          $(input).blur();
        },
        success: function (data) {
          alert("Successful comment");
          $(input).val("");
          $(input).blur();
        }
      });
    }
  });

发布评论。在views.py中,我保存了评论:

def comment(request, letnik_id, classes_id, subject_id):
try:
    if request.method == 'POST':
        exam_id = request.POST.get('exam_id')
        exam = get_object_or_404(Exam, id=exam_id)
        comment = request.POST.get('post')
        comment = comment.strip()
        if len(comment) > 0:
            instance = ExamComment(
                exam=exam,
                comment=comment,
                comment_user=request.user)
            instance.save()
            return redirect('subject_id', letnik_id=letnik_id, classes_id=classes_id, subject_id=subject_id)
        html = ''
        for comment in exam.get_comments():
            html = '{0}{1}'.format(html, render_to_string('exam_partial_comment.html', {'comment': comment}))
        return HttpResponse(html)
    else:
        return HttpResponseBadRequest()
except Exception:
    return HttpResponseBadRequest()

也没有:return redirect('subject_id', letnik_id=letnik_id, classes_id=classes_id, subject_id=subject_id) 这段代码,我会得到error400,我不会得到成功提醒...

1 个答案:

答案 0 :(得分:1)

首先,您需要JsonResponse函数而不是HttpResponse。使用JsonResponse,您只需传递一个字典对象,其中包含您要在页面中更新的注释,例如:

from django.http import JsonResponse
if request.method == 'POST':
    #...
    if len(comment) > 0:
        #...saving...
    comments = ExamComment.objects.filter(exams=exams, comment_user=request.user)
    newcomments = {comments:[]}
    for comment in comments:
        newcomments[comments].append(comment) 
    return JsonResponse(newcomments)
else:
    return HttpResponseBadRequest()

这种方式不涉及渲染,您将新(和旧)注释返回到模板。接下来,你需要在ajax成功之后重建你的评论div(我不知道名字):

success: function (data) {
      alert("Successful comment");
      $(input).val("");
      $(input).blur();
      var div = document.getElementById('yourCommentDivName');
      newcomments = ''
      for(i;i<data.comments.length;i++){
         newcomments = newcomments + '<p>' + data.comments[i] + '</p>'
      }
      div.innerHTML = div.innerHTML + newcomments;
    }

那就是它。评论:代码未经过测试;如果你经常做这种事情,你应该研究一些开箱即用的javascript库,作为反应。陡峭的学习曲线,但一旦你明白它是一个救生员;最后一点是,除了东西之外,避免这种尝试。这使得调试更加困难,从长远来看对健康有害。只有你真的必须这样做,我认为不是这样。

希望它有所帮助!