【发布时间】:2022-01-07 14:20:12
【问题描述】:
我有一个 Django 应用程序,我想在其中显示一个包含用户帖子的页面,其他用户可以通过单击位于锚标记中的 Font Awesome 图标来喜欢这些用户帖子。当用户喜欢帖子时,图标类应从fa-heart 更改为fa-heart-o,反之亦然。为了实现这一点,图标上的单击事件发出 Ajax 请求。这会更改图标并增加/减少点赞数。
我有这样的 FBV:
#feeds/views.py
@login_required
def like(request):
post_id = request.GET.get("post_id", "")
user = request.user
post = Post.objects.get(pk=post_id)
liked= False
like = Like.objects.filter(user=user, post=post)
if like:
like.delete()
else:
liked = True
Like.objects.create(user=user, post=post)
resp = {
'liked':liked
}
response = json.dumps(resp)
return HttpResponse(response, content_type = "application/json")
在urls.py:
urlpatterns=[
path('like/', views.like, name='like'),
]
这是模板
{% for post in posts %}
......
</li>
<li>
{% if post in liked_post %}
<span class="like" data-toggle="tooltip" title="Unlike">
<a href="{% url 'like' %}" id="like" post_id="{{ post.id }}"><i class="fa fa-heart"></i></a>
<ins>{{ post.likes.count }}</ins>
</span>
</a>
{% else %}
<span class="like" data-toggle="tooltip" title="Like">
<a href="{% url 'like' %}" id="like" post_id="{{ post.id }}"><i class="fa fa-heart-o"></i></a>
<ins>{{ post.likes.count }}</ins>
</span>
</a>
{% endif %}
</li>
...
{% endfor %}
这是 Ajax 调用。
$('#like').click(function (e) {
console.log('requested !')
var _this = $(this);
e.preventDefault();
$.ajax({
type: "GET",
url: "{% url 'like' %}",
data:{
post_id: _this.attr('post_id')
}
success: function (res) {
if (res.liked){
icon = _this.find("i");
icon.toggleClass("fa-heart fa-heart-o");
console.log('liked');
}
else{
icon = _this.find("i");
icon.toggleClass("fa-heart-o fa-heart");
console.log('unliked');
}
}
});
});
现在的问题是:每当我点击心形图标时,页面都会被重定向到/like(我认为不会发生,因为使用了preventDefault();),我不能喜欢这个帖子。
我怎么能解决这个问题?我尝试过不同的解决方案,例如:
How to change icon using ajax call
Change anchor text and icon with jquery
How can I change an element's class with JavaScript?
Change the color of the icon in jquery (django project)
但这些都不适合我。所以问题是我该如何实现呢?另外,ajax 调用成功后如何更改点赞数?
【问题讨论】:
-
嗨,你喜欢的是 class 而不是 id 。所以把
#like改成.like -
@Swati
like是<span>标签下<a>标签中的一个类。
标签: javascript html jquery django ajax