2017-05-01 2 views
1

댓글을 게시 한 직후 사용자 게시물을 게시하고 싶습니다. 이미 아약스에서 댓글을 업로드했는데, 어떻게 상쾌하게하지 않고도 사용자에게 표시 할 수 있습니까? 이 아약스 코드는 다음과 같습니다.새로 고침하지 않고 댓글보기

$(".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) 이 코드를 대신 HttpResponse에의 JsonResponse 기능을 필요로 ...

답변

1

먼저 내가 error400을 얻을 것입니다 그리고 난 성공 경고를 얻을 wouldn`t . 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() 

당신이 당신의 템플릿에 다시 새로운 (오래된) 주석을 반환이 반군 렌더링이 없으며,이 방법 . 다음으로 아약스 성공 후 주석 부분을 다시 작성해야합니다 (이름을 모르겠습니다).

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; 
    } 

글쎄, 맞습니다. 코멘트 : 코드는 테스트되지 않습니다. 이런 종류의 일을 많이하는 경우, 반응을 일으키는 자바 스크립트 라이브러리를 살펴 봐야합니다. 가파른 학습 곡선,하지만 일단 당신이 그것을 이해하면 그것은 생명의 은인입니다; 마지막으로, 음, 물건을 제외하고 시도하지 마십시오. 이렇게하면 디버깅이 어려워지고 장기적으로 건강에 좋지 않습니다. 정말로 필요한 경우에만이 작업을 수행하십시오. 그렇다고 생각하지 않습니다.

희망이 있습니다.

+0

다른 모든 것은 이미 렌더링되었으므로 모두 함께 사용하는 것이 아니라 새로운 설명 만 렌더링 할 수 있습니까? – zzbil

+0

예! 뷰의 모든 주석을 쿼리하는 대신 JsonResponse ({comment : comment})와 같은 사전 내에서 JsonResponse로 새로운 주석을 다시 보내면됩니다. 아약스 성공 함수에서 for 루프를 삭제하고 diventinnerHTML = div.innerHTML + comment; 네, 이쪽으로는 훨씬 좋습니다. – Tico

+0

정말 고마워요. 그러나 문제가 있습니다. 내가 아래로 이것을 포함하면 : return redirect ('subject_id', letnik_id = letnik_id, classes_id = classes_id, subject_id = subject_id)보기에서, 나는 아약스에서 성공하지 못한다. 왜 그런지 알게됩니까? 오류 400 (나쁜 요청)이 발생하지만 새로 고침 후 주석이 게시 됨 – zzbil

관련 문제