我想在用戶點擊相應的評論鏈接時加載特定文章的所有評論。我想用Jquery Ajax來做到這一點,而不刷新頁面,但無法實現我的動機。我在這裏分享了我的想法。如果這不是相關的方法,請給我建議另一種方法。使用jquery ajax在django中動態加載評論
//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'),]
什麼預期的結果?你有什麼? – pancho018
我沒有收到任何輸出。該頁面只是刷新添加/#/到原來的網址,並沒有做任何事情。 –
我希望點擊評論鏈接時,我會看到一個下拉列表,顯示該特定文章的所有評論(如quora)。 –