我目前正在處理來自 cs50w 的專案 4 網路,我必須實作關注/取消關注按鈕。我定義了 URL、視圖中的函式、html 和 JavaScript 代碼,但是當我單擊關注/取消關注按鈕時,我不明白如何在 JavaScript 中動態獲取用戶 ID。
這是我的代碼:
urls.py path("profile/<int:author_id>/", views.profile, name="profile"),
path("follow/<int:author_id>/", views.follow, name="follow")
views.py
def follow(request, author_id):
try:
foo = 'follow'
logged_user = User.objects.get(id=request.user.id)
following_user = User.objects.get(id=author_id)
follower = Follower.objects.get_or_create(follower=logged_user, following=following_user)[1]
a = following_user.id
if not follower:
Follower.objects.filter(follower=logged_user, following=following_user).delete()
foo = 'unfollow'
all_followers = Follower.objects.filter(following = following_user).count()
except KeyError:
return HttpResponseBadRequest("Bad request")
return JsonResponse({"foo": foo, "all_followers": all_followers})
profile.html
<center>
<h2>{{ profile_user.username }}</h2>
<h6 class="card-text"><span id="sp_following">{{ following }}</span> Following</h6>
<h6 class="card-text"><span id="sp_followers">{{ followers}}</span> Followers</h6>
<div>
{% if user.is_authenticated and user.id != profile_user.id %}
<p class="card-text">
{% if is_following > 0 %}
<button id="btnfollow" data-id="{{user_profile.id}}" type="button" class="btn btn-primary">Unfollow</button>
{% else %}
<button id="btnfollow" data-id="{{user_profile.id}}" type="button" class="btn btn-outline-primary">Follow</button>
{%endif%}
</p>
{%endif%}
</div>
models.py
class Follower(models.Model):
follower = models.ForeignKey(User, on_delete=models.CASCADE, default=None, related_name="follower_user")
following = models.ForeignKey(User, on_delete=models.CASCADE, default=None, related_name="following_user")
index.js
document.addEventListener('DOMContentLoaded', function () {
if (document.getElementById('btnfollow')) {
document.querySelector('#btnfollow').addEventListener('click', function (event) {
fetch(`/follow/${WHAT NEEDS TO BE ADDED HERE?}/`)
.then(response => response.json())
.then(data => {
document.querySelector('#sp_followers').innerHTML = data.all_followers;
if (data.foo == 'follow') {
this.innerHTML = 'Unfollow';
this.className = 'btn btn-primary';
} else {
this.innerHTML = 'Follow';
this.className = 'btn btn-outline-primary';
}
})
})
}
})
在這行代碼中,fetch(`/follow/${???}/`)我嘗試了很多東西(例如:this.dataset.id、id、author_id 等),但都沒有奏效。此外,例如,如果我在 URL 中手動插入一個現有的(在資料庫中)id,fetch(`/follow/2/`)那么它有點作業,但我需要它根據我點擊的特定用戶動態地進行。
uj5u.com熱心網友回復:
您可以通過兩種不同的方式獲取您的案例中的用戶 ID:
onclick在單擊事件時,通過參考傳遞動態 ID將函式分配給處理程式{{user_profile.id}}- 添加事件監聽器,通過
this關鍵字獲取標簽名稱,然后訪問data-id屬性即this.dataset.id參考
提示:您需要將按鈕 ID 替換為類名,因為id在 DOM 級別上應該是唯一的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/490996.html
標籤:javascript 网址 cs50 网址提取
