![](/img/trans.png)
[英]Why does my js work incorrectly if i do not reload the page. This is for CS50 Web Project 3
[英]CS50 Web - Project 4 Network
我目前正在研究 CS50 Web 項目 4 - 網絡。 任務是設計一個類似推特的網絡。 目前,我被困在Like-Function。
我有一個贊按鈕和一個贊計數器。 當我點擊喜歡按鈕時,頁面上的計數器顯示“未定義”。 但是當我重新加載頁面時,一切都很好,喜歡計數顯示了正確的喜歡數量,而且喜歡按鈕已更改為不同按鈕。 有誰知道有什么問題? 我現在被困了好幾天,無法弄清楚。 任何幫助深表感謝。
這是我的代碼:
視圖.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")
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 %}
"done"
,而不是具有likes
屬性的對象。return JSONResponse({"likes": post.likes})
。fetch()
返回的值是一個響應。 (您正在嘗試訪問likes
它。)您需要等待res.json()
將 JSON 響應解碼為對象。 (同時,我們可以刪除代碼中的一些重復。)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.