[英]CS50 Web - Project 4 Network
I am currently working on the CS50 Web Project 4 - Network.我目前正在研究 CS50 Web 项目 4 - 网络。 The task is to design a twitter-like Network.
任务是设计一个类似推特的网络。 Currently, I am stuck at the Like-Function.
目前,我被困在Like-Function。
I have a like-button and a counter of the likes.我有一个赞按钮和一个赞计数器。 When I click the like-button, the counter on the page says "undefined".
当我点击喜欢按钮时,页面上的计数器显示“未定义”。 But when I reload the page, everything is fine and the like-count shows the right number of likes and also the like button has changed to an unlike button.
但是当我重新加载页面时,一切都很好,喜欢计数显示了正确的喜欢数量,而且喜欢按钮已更改为不同按钮。 Does anyone have an idea what the issues?
有谁知道有什么问题? I am stuck for days now and cannot figure it out.
我现在被困了好几天,无法弄清楚。 Any help is much appreciated.
任何帮助深表感谢。
Here is my code:这是我的代码:
views.py视图.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 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;
});
}
and on my html:在我的 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 %}
"done"
, not an object that would have a likes
attribute."done"
,而不是具有likes
属性的对象。return JSONResponse({"likes": post.likes})
instead.return JSONResponse({"likes": post.likes})
。fetch()
returns is a Response. fetch()
返回的值是一个响应。 (You're trying to access likes
on it.) You'll need to await on res.json()
to decode a JSON response into an object. likes
它。)您需要等待res.json()
将 JSON 响应解码为对象。 (While at it, we can remove a bit of repetition in the code.) function likeOrUnlike(id, like) {
fetch(`/like/${id}`, {
method: "PUT",
body: JSON.stringify({ like: !!like }),
})
.then((resp) => resp.json())
.then((post) => {
document.querySelector(`#like_count${id}`).innerHTML = post.likes;
});
}
function like(id) {
likeOrUnlike(id, true);
}
function unlike(id) {
likeOrUnlike(id, false);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.