Django ajax评论使用Jquery?

Naz*_*han 2 django jquery django-templates django-views

我想实现一个ajax评论系统.

urls.py:

(r'^comment/(\d+)/$', comments),
Run Code Online (Sandbox Code Playgroud)

views.py:

def comments(request,feed):
  if request.method == 'POST':
    feed=Feed.objects.get(pk=feed)
    form = CommentForm(request.POST)
    if form.is_valid():
       comment, created = Comment.objects.get_or_create(
          feed=feed,
          msg=form.cleaned_data['msg'],
          ip=request.META['REMOTE_ADDR']
        )

    comments=Comment.objects.filter(feed=feed)
    form=CommentForm()
    variables=RequestContext(request,{'comments': comments,'feed': feed,'form':form,})
    if 'HTTP_REFERER' in request.META:
      return HttpResponseRedirect(request.META['HTTP_REFERER'])
    return render_to_response('comment_page.html', variables )
    #return HttpResponseRedirect('/view/')
  else:
    form=CommentForm()
    feed=Feed.objects.get(pk=feed)
    comments=Comment.objects.filter(feed=feed).reverse()


    variables=RequestContext(request,{'comments': comments,'feed': feed,'form':form,})
    return render_to_response('comment_page.html', variables )
Run Code Online (Sandbox Code Playgroud)

模板:

<div id="commentbox" style="display:none;">
      <form class="comment" method="post" action="/comment/{{feed.id}}/">
               {{cform.as_p}}
               <input class="post" type="submit" value="post" />
               </form>
              </div>
              </br>
              <h3></h3><button class="ccc">Show/Hide Comment</button> {{feed.comment_set.count}} Comments
              <div id="commentlist" class="commentlist" style="padding-left:10px;"><ul style="list-style-type:square;">
              {% for c in feed.comment_set.all %}

              <li>{{c.msg}}</li>

              {% endfor %}
              </ul>
              </div>
Run Code Online (Sandbox Code Playgroud)

我应该包含哪些代码来在没有页面刷新的情况下将注释添加到commentlist li字段中.我是ajax的新手.请帮忙.谢谢

Ble*_*der 6

这就是我要做的事情:

保留HTML原样,因为它适用于没有JavaScript的人.在JavaScript中,当用户提交表单时,请阻止它实际发生:

$('#commentbox form').submit(function(e) {
    e.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)

现在,当按下按钮时,阻止默认行为并通过AJAX提交表单:

$('#commentbox form').submit(function(e) {
    e.preventDefault();

    $.ajax({
        type: 'post',
        url: $(this).parent().attr('action'),
        data: $(this).parent().serialize(),
    }).done(function(data) {
        alert('The AJAX is done, and the server said ' + data);
    });
});
Run Code Online (Sandbox Code Playgroud)

  • 您最好在表单上"提交"事件,而不是在"提交"按钮上"单击". (3认同)