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

发布于 2025-02-06 08:01:56 字数 2909 浏览 2 评论 0 原文

我目前正在从CS50W上使用项目4网络,并且必须实现“关注/取消关注”按钮。我定义了URL,视图中的功能,HTML和JavaScript代码,但是当我单击“关注/untollow”按钮时,我不明白如何在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';
            }
        })
    })

}

})

在代码 fetth(`/clost/$ {????}/`)我尝试了一堆事情(ex:ex:this.dataset.id,id,id) ,furety_id等),但无效。另外,如果我在URL中手动插入现有的(在db中)ID,例如 fetch(`/laster/2/`)我点击的特定用户。

I'm currently working on project 4 network, from cs50w and I have to implement the follow/unfollow button. I defined the URLs, the function in views, the html and the JavaScript code, but I don't understand how to dynamically fetch the user id in JavaScript when I click the follow/unfollow button.

here is my code:

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';
            }
        })
    })

}

})

In this line of code fetch(`/follow/${???}/`) i tried a bunch of things (ex: this.dataset.id, id, author_id, etc) but none worked. Also if I manually insert an existing (in the DB) id in the URL for example fetch(`/follow/2/`) then it sort of works, but I need it to be dynamically based on the specific user I click.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

染柒℉ 2025-02-13 08:01:56

您可以在情况下以两种不同的方式获取用户ID:

  • 在单击事件时,通过通过 {{user_profile.id}} onclick 处理程序中。 >
  • 代码 标记名称关键字,然后访问 data-id 属性IE this.dataset.id 参考

提示:您需要用类名称替换按钮ID,导致 id id id < /代码>在DOM级别上应是唯一的。

You can get the user ID in your case in two different ways:

  • On click event, assign a function into the onclick handler by passing the dynamic ID by {{user_profile.id}} reference
  • Add an event listener, get the tag name by this keyword then access the data-id attribute i.e. this.dataset.id reference

Tip: You need to replace the button ID with the class name cause the id should be unique on the DOM level.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文