You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript实现关注/取关功能时如何动态获取目标用户ID

问题原因

你用this.dataset.id拿不到值的核心原因是模板变量名写错了:视图传给模板的当前页面对应用户对象是profile_user,但按钮的data-id属性里写的是{{user_profile.id}},这个变量不存在,渲染后data-id是空值,JS自然读不到正确的用户ID。

修复步骤

按以下顺序修改即可:

  • 修正模板里的data属性变量
    找到profile.html里两个关注按钮的代码,把错误的data-id="{{user_profile.id}}"改成data-id="{{ profile_user.id }}",修正后的按钮代码示例:
    {% if is_following > 0 %}
        <button id="btnfollow" data-id="{{ profile_user.id }}" type="button" class="btn btn-primary">Unfollow</button>
    {% else %}
        <button id="btnfollow" data-id="{{ profile_user.id }}" type="button" class="btn btn-outline-primary">Follow</button>
    {%endif%}
    
    记得在页面中加上{% csrf_token %}模板标签,否则Django会拦截后续的异步请求报403错误。
  • 补全JS的fetch逻辑
    你原来的JS代码末尾多了一个冗余的})会触发语法错误,先删掉多余括号,再补全ID读取逻辑,同时加上Django要求的CSRF请求头,修改后的完整JS代码:
    document.addEventListener('DOMContentLoaded', function () {
        const followBtn = document.querySelector('#btnfollow');
        if (followBtn) {
            followBtn.addEventListener('click', function () {
                // 直接从当前点击按钮的dataset属性取目标用户ID
                const targetUserId = this.dataset.id;
                fetch(`/follow/${targetUserId}/`, {
                    method: 'POST',
                    headers: {
                        "X-CSRFToken": document.querySelector('[name=csrfmiddlewaretoken]').value,
                    }
                })
                .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';
                    }
                })
            })
        }
    })
    
  • 优化视图异常捕获
    你现在的视图只捕获了KeyError,实际如果传入的用户ID不存在会抛出User.DoesNotExist异常,建议补上捕获逻辑,同时给follow接口加上@login_required装饰器,限制未登录用户不能调用接口。
验证方法

改完后打开浏览器开发者工具,检查元素看关注按钮的data-id属性是否正确渲染为当前profile页的用户数字ID,点击按钮时查看网络请求地址是否为/follow/正确用户ID/,正常情况下按钮文字、粉丝计数会同步更新。

内容的提问来源于stack exchange,提问作者stefanp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 13:15:35