问题是由于我的 django twitter 克隆应用程序中的 ajax 实现造成的,单击“喜欢”按钮后每个帖子的“喜欢”计数显示相同。但在页面刷新后就可以了。我即将解决问题,但不知何故陷入困境。
查看:
def add_like(request):
if request.method == 'GET':
ans_id = request.GET['id']
user = request.user.profile
liked_tweet = get_object_or_404(Tweet, pk=ans_id)
if ans_id:
# creating instance by sending the Like table fields
instance, created = Like.objects.get_or_create(liker=user, liked_tweet=liked_tweet)
ans = Tweet.objects.get(id=(int(ans_id)))
if ans:
likes = ans.likes + 1
ans.likes = likes
ans.save()
# returns the likes field of a tweet post
return HttpResponse(likes)
HttpResponse 正在发送点赞,我猜这会产生问题。
模板:
{% for tw in tweets %}
<div class="blog-post">
<p>
{{ tw.content|safe }}<br><hr>
<small class="small">
লিখসে -
<!-- in the "href" we can pass data like "pk", accessing by the structure the current object is based on-->
<a href="{% url 'profile' pk=tw.tweeter.user.pk %}">{{ tw.tweeter.user.username|capfirst }}</a>
</small>
</p>
{% if user.is_authenticated %}
<button class="btn btn-default likes-button" type="button"
data-ansid="{{ tw.pk }}">Like</button>
<i> Total Likes: </i><em class="like_count">{{ tw.likes }}</em>
{% endif %}
</div>
ajax 脚本:
$(".likes-button").click(function(e) {
if ($(this).html() == "Like") {
$(this).html('Unlike');
//alert("js working");
// error was there for "data" insted of "attr"
var ansid = $(this).attr("data-ansid");
$.ajax({
url: '{% url "add_like" %}',
type: 'get',
data: {id: ansid}
}).done(function (data) {
alert("success");
$('.like_count').html(data);
//$('#likes').hide();
}).fail(function (err) {
alert(err);
});
}
提前致谢。
最佳答案
我认为 Sayse 的第一条评论就给出了你的答案。我只是想给出更多解释。
因此,您所做的就是在成功的 ajax 请求之后,在任何具有名为 .like_count
的类的元素中,将现有的 Like count 替换为从 ajax 获取的数据。
checkin 您的代码 $('.like_count').html(data);
这会选择所有具有 like_count
类的元素,并且更改 html。
相反,您应该做的是在成功的 ajax 之后,仅更改一处数据。 您需要选择合适的jquery选择器。
类似于 .closest()
可以使用。在这种情况下,请使用(以下代码未测试)$(this).closest('.like_count').html(data);
来追加'like count'在适当的元素。
您还可以根据 id 为每个“喜欢计数”元素分配动态 ID,然后使用 exect ID 选择器。
希望这有帮助。
干杯!
关于javascript - ajax 之类的计数在 django 中的每个帖子中显示相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38304934/