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

如何通过代码获取SharePoint人员选择器中各用户的经理?

Fixes & Improvements for Retrieving Managers from SharePoint People Picker

Let's break down the issues in your code and refactor it to work more reliably with better practices:

Key Issues in Your Current Code

  • Unscoped Variables: currusr and managerName aren't declared with var/let/const, leading to global scope pollution that can cause unexpected behavior in loops.
  • Synchronous AJAX Blocking: Using async: false freezes the browser until all requests complete – this hurts user experience and is generally discouraged.
  • Unfiltered Split Results: Splitting on ; can leave empty strings in your array (if the last entry ends with a semicolon), which will trigger unnecessary API calls.
  • Incorrect XML Selector: The > HTML entity shouldn't be used in jQuery selectors; use the direct child selector > instead. Also, :contains('Manager') can match unintended properties (e.g., ManagerAssistant), so we should use an exact match.

Refactored Code (Asynchronous & Robust)

// Get the people picker value and clean up the array
var usr = $("textarea[title='People Picker']:first").val();
var userArray = usr.split(";").filter(function(user) {
    // Remove empty strings from the split result
    return user.trim() !== "";
});

// Function to fetch manager with async/await for cleaner flow
async function getManager(userAccount) {
    return new Promise(function(resolve, reject) {
        $().SPServices({
            operation: "GetUserProfileByName",
            async: true, // Use asynchronous requests
            AccountName: userAccount.trim(),
            completefunc: function(xData, status) {
                if (status === "success") {
                    // Exact match for the Manager property
                    var managerNode = $(xData.responseXML).find("PropertyData").filter(function() {
                        return $(this).find("Name").text() === "Manager";
                    });
                    var managerName = managerNode.find("Values").text().trim();
                    resolve(managerName);
                } else {
                    reject("Failed to fetch profile for " + userAccount);
                }
            },
            errorfunc: function(xhr, errorText, thrownError) {
                reject(errorText);
            }
        });
    });
}

// Process each user in sequence (or parallel if preferred)
async function processUsers() {
    for (let user of userArray) {
        try {
            let manager = await getManager(user);
            alert(`Manager for ${user}: ${manager}`);
            // Replace alert with your actual logic here
        } catch (error) {
            console.error(error);
            alert(`Error fetching manager for ${user}: ${error}`);
        }
    }
}

// Kick off the process
processUsers();

Additional Notes

  • Async/Await: This makes asynchronous code read like synchronous code without blocking the browser.
  • Error Handling: Added error functions and try/catch blocks to handle failed API calls gracefully.
  • Exact Property Match: Using filter() to check the Name text exactly ensures we only target the Manager property.
  • Cleaned User Input: Trimming and filtering empty entries prevents unnecessary API calls for invalid user strings.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:27:39