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

SharePoint托管加载项:用JS(优先REST API)获取用户及经理信息填充人员选择器

我刚好在SharePoint托管加载项里实现过一模一样的需求,给你一套经过验证的JavaScript样板代码,全程用REST API来获取用户数据,直接就能用:

核心实现步骤
  • 先加载SharePoint必要的客户端脚本(比如sp.js、sp.userprofiles.js),确保PeoplePicker控件能正常操作
  • 通过REST API获取当前用户的完整配置文件,拿到用户自己的信息和经理的账号名
  • 再用经理的账号名请求其用户配置文件
  • 封装通用方法来填充PeoplePicker控件,避免重复代码
  • 页面加载完成后自动触发整个流程
完整代码示例
// 等待页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 加载SharePoint客户端脚本依赖
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {
        SP.SOD.executeFunc('sp.userprofiles.js', 'SP.UserProfiles.PeopleManager', initPeoplePickerData);
    });
});

function initPeoplePickerData() {
    // 1. 获取当前用户的用户配置文件
    getCurrentUserProfile()
        .then(function(currentUser) {
            // 填充Requestor和Payee(这里假设两者都是当前用户,可根据需求调整)
            fillPeoplePicker('Requestor', currentUser);
            fillPeoplePicker('Payee', currentUser);

            // 2. 如果当前用户有经理,获取经理的配置文件并填充Manager控件
            if (currentUser.Manager) {
                return getUserProfileByAccountName(currentUser.Manager.AccountName);
            } else {
                console.log('当前用户未设置经理');
                return Promise.resolve(null);
            }
        })
        .then(function(managerUser) {
            if (managerUser) {
                fillPeoplePicker('Manager', managerUser);
            }
        })
        .catch(function(error) {
            console.error('加载用户数据失败:', error);
            alert('加载用户信息时出现错误,请刷新页面重试');
        });
}

// 获取当前用户的用户配置文件
function getCurrentUserProfile() {
    return new Promise(function(resolve, reject) {
        var restUrl = _spPageContextInfo.webAbsoluteUrl + '/_api/SP.UserProfiles.PeopleManager/GetMyProperties';

        fetch(restUrl, {
            method: 'GET',
            headers: {
                'Accept': 'application/json;odata=nometadata'
            }
        })
        .then(function(response) {
            if (!response.ok) {
                throw new Error('HTTP error! status: ' + response.status);
            }
            return response.json();
        })
        .then(function(data) {
            // 整理需要的用户数据
            var user = {
                AccountName: data.AccountName,
                DisplayName: data.DisplayName,
                Email: data.Email,
                Manager: data.Manager ? {
                    AccountName: data.Manager.AccountName,
                    DisplayName: data.Manager.DisplayName
                } : null
            };
            resolve(user);
        })
        .catch(reject);
    });
}

// 根据账号名获取指定用户的配置文件
function getUserProfileByAccountName(accountName) {
    return new Promise(function(resolve, reject) {
        // 对账号名进行URL编码,避免特殊字符报错
        var encodedAccountName = encodeURIComponent(accountName);
        var restUrl = _spPageContextInfo.webAbsoluteUrl + '/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)?@v=\'' + encodedAccountName + '\'';

        fetch(restUrl, {
            method: 'GET',
            headers: {
                'Accept': 'application/json;odata=nometadata'
            }
        })
        .then(function(response) {
            if (!response.ok) {
                throw new Error('HTTP error! status: ' + response.status);
            }
            return response.json();
        })
        .then(function(data) {
            var user = {
                AccountName: data.AccountName,
                DisplayName: data.DisplayName,
                Email: data.Email
            };
            resolve(user);
        })
        .catch(reject);
    });
}

// 填充PeoplePicker控件的通用方法
function fillPeoplePicker(pickerId, userData) {
    // 获取PeoplePicker控件实例(SharePoint自动生成的TopSpan后缀)
    var peoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[pickerId + '_TopSpan'];
    if (!peoplePicker) {
        console.error('找不到ID为' + pickerId + '的PeoplePicker控件');
        return;
    }

    // 清空控件已有值
    peoplePicker.DeleteAllUnresolvedUsers();

    // 构造符合要求的用户实体
    var userEntity = {
        Key: userData.AccountName,
        DisplayText: userData.DisplayName,
        Description: userData.Email,
        EntityType: 'User',
        IsResolved: true,
        EntityData: {
            Email: userData.Email,
            PrincipalType: 1 // 1代表用户类型
        },
        MultipleMatches: false
    };

    // 添加用户到控件并触发UI更新
    peoplePicker.AddUserKeys([userData.AccountName]);
    peoplePicker.ProcessUserAdded(userEntity);
}
关键注意事项
  • 控件ID对应:代码里的Requestor、Payee、Manager要和你页面上PeoplePicker控件的基础ID完全一致(比如控件ID是Requestor,SharePoint会自动生成Requestor_TopSpan,代码里已经处理了这个后缀)
  • 权限要求:确保当前用户有读取用户配置文件的权限(默认权限一般足够,特殊环境可能需要调整站点权限)
  • 跨域处理:如果你的托管加载项是跨域部署的,可能需要用SP.RequestExecutor替代fetch来处理跨域请求,不过现代浏览器大多支持CORS,一般不需要额外操作
  • 自定义调整:如果Requestor和Payee不是当前用户,你可以修改代码里的逻辑,传入对应的用户账号名获取数据即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:53:49