首页 > 解决方案 > 如何在 postlistview 和 postdetailview 中使用 ajax

问题描述

我有一个帖子详细信息,我成功地使用 ajax 来喜欢帖子部分,所以如果有人喜欢这个帖子,它会异步引用该部分。但是我不能在帖子列表视图中做到这一点。它不能异步工作。谁能帮我解决它。

这是我的views.py:

@login_required
def like_post(request):
# posts = get_object_or_404(Post, id=request.POST.get('post_id'))
posts = get_object_or_404(post, id=request.POST.get('id'))

is_liked = False
if posts.likes.filter(id=request.user.id).exists():
    posts.likes.remove(request.user)
    is_liked = False
else:
    posts.likes.add(request.user)
    is_liked = True
    notify.send(request.user, recipient=posts.author, actor=request.user, verb='liked your post.', target=posts, nf_type='liked_by_one_user')

context = {'posts':posts, 'is_liked': is_liked, 'total_likes': posts.total_likes(),}



if request.is_ajax():
    html = render_to_string('blog/like_section.html', context, request=request)
    return JsonResponse({'form': html})

if request.is_ajax():
    html = render_to_string('blog/likes_home.html', context, request=request)
    return JsonResponse({'form': html})

likes_home 部分用于 postlistview

我的 likes_home.html:

<script>
$(document).on('click', '#like', function(event){
  event.preventDefault();
  var pk = $(this).attr('value');
  $.ajax({
    type: 'POST',
    url: '{% url "like_post" %}',
    data: {'id':pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
    dataType: 'json',
    success: function(response){
      $('#like-home').html(response['form'])
      console.log($('#like-home').html(response['form']));
    },
    error: function(rs, e){
    console.log(rs.responseText);
    },
 });
});
</script>

<form action="{% url 'like_post' %}" method="POST">
{% csrf_token %}
{% if post.is_liked %}
<button type="submit" id="like" name="post_id" value="{{ post.id }}" class="btn btn-danger">dislike</button>
{% else %}
<button type="submit" id="like" name="post_id" value="{{ post.id }}" class="btn btn-primary">like</button>
{% endif %}
</form>

我的 postlist.html 是:

<p><a class="article-content" href="{% url 'post-detail' pk=post.pk %}" >{{ post.content }}</a></p>
      <a href="{% url 'post-likes' pk=post.pk %}">
        {{ post.total_likes }}like{{ post.total_likes|pluralize}}
      </a>
      <a href="{% url 'post-detail' pk=post.pk %}">{{ post.comments.count }}comment{{ post.comments.count|pluralize }}</a>
      <div id="share-section">
          {% include 'blog/share.html' %}
      </div>
        <div id="like-home">
        {% include 'blog/likes_home.html' %}
    </div>

标签: jqueryjsondjangoajax

解决方案


我想这是因为:

if request.is_ajax():
    html = render_to_string('blog/like_section.html', context, request=request)
    return JsonResponse({'form': html})

if request.is_ajax():
    html = render_to_string('blog/likes_home.html', context, request=request)
    return JsonResponse({'form': html})

第二条if语句将永远不会运行,因为您具有相同的条件并且return在 first 中if,因此该函数通过 refresh 完成了它的工作blog/like_section.html


推荐阅读