【问题标题】:Django ajax comments using Jquery?使用 Jquery 的 Django ajax 评论?
【发布时间】:2011-09-03 17:55:13
【问题描述】:

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

urls.py:

(r'^comment/(\d+)/$', comments),

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 )

模板:

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

在不刷新页面的情况下,我应该包含哪些代码才能将 cmets 添加到评论列表 li 字段中。我是ajax新手。请帮忙。谢谢

【问题讨论】:

    标签: django jquery django-templates django-views


    【解决方案1】:

    我会这样做:

    保持 HTML 不变,因为它适用于没有 JavaScript 的人。在你的 JavaScript 中,当用户提交表单时,阻止它实际发生:

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

    现在,当按下按钮时,阻止默认行为并通过 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);
        });
    });
    

    【讨论】:

    • 当我将上面的代码插入到我的 html 中时,“发布”/提交按钮没有被按下。为什么会这样。?
    • 然后删除前两行。我是手写的,所以测试已经完成了......
    • 您最好在表单上使用“提交”事件,而不是在提交按钮上“点击”。
    猜你喜欢
    • 2014-04-19
    • 1970-01-01
    • 2017-01-28
    • 1970-01-01
    • 2019-02-23
    • 2020-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多