【发布时间】:2021-12-26 14:05:14
【问题描述】:
我目前正在研究 CS50 Web 项目 4 - 网络。任务是设计一个类似推特的网络。目前,我被困在 Like-Function 中。
我有一个点赞按钮和一个点赞计数器。当我单击赞按钮时,页面上的计数器显示“未定义”。但是当我重新加载页面时,一切都很好,点赞数显示正确的点赞数,点赞按钮也变成了不喜欢的按钮。有谁知道有什么问题?我现在被困了好几天,无法弄清楚。非常感谢任何帮助。
这是我的代码:
views.py
@csrf_exempt
def like(request, post_id):
post = Post.objects.get(id=post_id)
if request.method == "GET":
return HttpResponseRedirect(reverse("index"))
if request.method == "PUT":
data = json.loads(request.body)
if data.get("like"):
Likes.objects.create(user=request.user, post=post)
post.likes = Likes.objects.filter(post=post).count()
else:
Likes.objects.filter(user=request.user, post=post).delete()
post.likes = Likes.objects.filter(post=post).count()
post.save()
return HttpResponse("done")
java.js
function like(id) {
fetch(`/like/${id}`, {
method: 'PUT',
body: JSON.stringify({
like: true
})
})
.then(post => {
document.querySelector(`#like_count${id}`).innerHTML = post.likes;
});
}
function unlike(id) {
fetch(`/like/${id}`, {
method: 'PUT',
body: JSON.stringify({
like: false
})
})
.then(post => {
document.querySelector(`#like_count${id}`).innerHTML = post.likes;
});
}
在我的 html 上:
<div id="like_count{{post.id}}">Likes: {{ post.likes }}</div>
{% if liked %}
<button class="btn btn-outline-danger" id="unlike_button{{post.id}}" onclick="unlike('{{ post.id }}')">Unlike</button>
{% else %}
<button class="btn btn-outline-primary" id="like_button{{post.id}}" onclick="like('{{ post.id }}')">Like</button>
{% endif %}
【问题讨论】:
标签: javascript python cs50