繁体   English   中英

如何在javascript中动态获取用户ID?

[英]How can I dynamically fetch user id in javascript?

我目前正在处理来自 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/`) ,那么它可以工作,但我需要它根据我单击的特定用户动态地进行。

您可以通过两种不同的方式获取您的案例中的用户 ID:

  • 在点击事件中,通过{{user_profile.id}} 引用传递动态 ID 将函数分配给onclick处理程序
  • 添加事件监听器,通过this关键字获取标签名称,然后访问data-id属性即this.dataset.id 引用

提示:您需要将按钮 ID 替换为类名,因为该id在 DOM 级别上应该是唯一的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM