【问题标题】:Load comments dynamically in django using jquery ajax使用 jquery ajax 在 django 中动态加载评论
【发布时间】:2017-09-04 15:45:31
【问题描述】:

当用户点击相应的 cmets 链接时,我想加载特定文章的所有 cmets。我想用 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>

<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>
//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'),]
 

【问题讨论】:

  • 预期的结果是什么?你得到了什么?
  • 我没有收到任何输出。页面只是刷新添加 /#/ 到原始 url 而没有做任何事情。
  • 我希望在单击 cmets 链接时,我会看到一个下拉列表,其中显示了该特定文章(如 quora)的所有 cmets。
  • @pancho018 我希望在单击 cmets 链接时,我会看到文章下方显示的所有 cmets。我将代码从 .parseJSON(response) 更改为 JSON.parse(response) 并且控制台没有抛出任何错误。但是,为了检查我的服务器是否返回任何响应,我在成功函数中编写了代码 console.log(response)。但是控制台没有显示任何结果。请问能解决这个问题吗

标签: jquery ajax django


【解决方案1】:

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

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

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

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

你能检查一下你的浏览器控制台是否有任何错误吗?

更新:

这对我有用:

indivisual_article.html

注意 {{article.articlecomment_set.count }} 获取 cmets 编号

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

【讨论】:

  • 我将代码从 .parseJSON(response) 更改为 JSON.parse(response) 并且控制台没有抛出任何错误。但是,为了检查我的服务器是否返回任何响应,我在成功函数中编写了代码 console.log(response)。但是控制台没有显示任何结果。如果你能解决这个问题,请。
  • 可能您在响应中收到错误并且未执行成功方法?首先,您可以尝试从POST更改为GET(如果您不更改服务器数据更合适)然后,在浏览器中写入url(articles/comment/?post_id=xx)并检查是否服务器响应正常。
  • 我尝试了上述更改,但没有效果。控制台没有响应任何东西,既没有任何响应,也没有任何错误。
猜你喜欢
  • 1970-01-01
  • 2011-09-03
  • 1970-01-01
  • 1970-01-01
  • 2012-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-02
相关资源
最近更新 更多