使用jquery ajax在django中动态加载注释

时间:2017-09-04 15:45:31

标签: jquery ajax django

我想在用户点击相应的评论链接时加载特定文章的所有评论。我想用Jquery Ajax做这个,而不刷新页面但不能实现我的动机。我在这里分享了我的想法。如果这不是相关的方法,请建议我另一种方法。



                       
                       
//articles/all_articles.html

<div class="infinite-container">
  <button onclick="topFunction()" id="myBtn" title="Go to top">Top</button> 
    {% for article in all_articles %}
     <div class="infinite-item">
       <ul id="posts_ul">
  {% include 'articles/indivisual_article.html' with article=article %} 
       </ul>
     </div>
     {% endfor %}
</div>

//articles/indivisual_articles.html

<a href="#" style="text-decoration: none;" class="comment" id="allcomments" value="{{article.id}}">
<span class="glyphicon glyphicon-comment"></span> 
{% trans 'Comment' %}
(<span class="comment-count">{{article.comments }}</span>)
</a><br>
<ol class="clearfix">
{% comment %} 
Place holder to load feed comments {% endcomment %}
</ol>
&#13;
&#13;
&#13;

&#13;
&#13;
<scripts type='text/javascript'> $('#allcomments').on("click",function(){
    var myvar= $(this).attr("value");
    var $el1= $(this);
    var $p1= $el1.parent();
    var $list= $p1.find(".clearfix");
      $.ajax(
       url: '/articles/comment/',
       type: 'POST',
       data:{post_id: myvar},
       dataType:'json',
       success: function(response) {
        queryset= .parseJSON(response);
          for(i=0; i<(queryset.count); i++){
                       value=response[i].comment
                       $list.html(<li>"{{value}}"= + value</li>).load()           
                     });
                     
                      
    }); 
    
</scripts>
&#13;
//views.py

@login_required    
def comment(request):
    if request.is_ajax():
        article_id= request.POST.get('post_id')
        article = Article.objects.get(id=article_id)
        comment=ArticleComment.objects.filter(post=article)
        response=serializers.serialize('json', list(comment), fields=('comment'))
        
        return HttpResponse(response, mimetype='application/json') 
        
//models.py

class Article(models.Model):
    title=models.CharField(max_length=250)
    post=models.TextField(max_length=4000)
    create_user=models.ForeignKey(User)
    

class ArticleComment(models.Model):
    post = models.ForeignKey(Article)
    comment=models.CharField(max_length=500)
    date = models.DateTimeField(auto_now_add=True)
    user = models.ForeignKey(User)    
    
//urls.py

urlpatterns= [url(r'^articles/comment/$', views.comment, name='art_comment'),]
 
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

我不确定打印评论的代码是否正常:

$list.html(<li>"{{value}}"= + value</li>).load() 

我认为html()期望htmlString作为一个参数,你可以试试吗?:

$list.html("<li>" + value + "</li>")

您可以检查浏览器控制台中是否有任何错误吗?

<强>更新

这对我有用:

<强> indivisual_article.html

请注意{{article.articlecomment_set.count}}以获取评论编号

{{ article.title }}
<a href="#" style="text-decoration: none;" class="comment" id="allcomments" value="{{article.id}}">
    <span class="glyphicon glyphicon-comment"></span>
    (<span class="comment-count">{{article.articlecomment_set.count }}</span>)
</a>
<br>

<ol class="clearfix">
    {% comment %}
        Place holder to load feed comments
    {% endcomment %}
</ol>

<强> view.py

我使用过JsonResponse和GET方法。

def comment(request):
    if request.is_ajax():
        article_id = request.GET.get('post_id')
        article = Article.objects.get(id=article_id)
        comments = ArticleComment.objects.filter(post=article)
        response = serializers.serialize('json', comments),
        return JsonResponse(response, safe=False)

<强>的Javascript

  • 更改脚本脚本
  • 在$ .ajax中缺少“{”( {
  • 使用GET
  • 将queryset.count更改为queryset.length,它是一个js数组
  • 然后,您必须从queryset获取评论名称:queryset [i] .fields.comment

你可以试试这个:

<script type='text/javascript'>
    $('#allcomments').on("click",function(){
        var myvar= $(this).attr("value");
        var $el1= $(this);
        var $p1= $el1.parent();
        var $list= $p1.find(".clearfix");
        $.ajax({
            url: '/articles/comment/',
            type: 'GET',
            data:{post_id: myvar},
            dataType:'json',
            success: function(response) {
                queryset= JSON.parse(response);
                var comment_list = '';
                for(i=0; i<queryset.length; i++){
                    comment_list = comment_list + "<li>"+queryset[i].fields.comment+"</li>";
                }
                $list.html(comment_list)
            }
        });
    });

</script>