如何通过代码获取SharePoint人员选择器中各用户的经理?
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:
currusrandmanagerNamearen't declared withvar/let/const, leading to global scope pollution that can cause unexpected behavior in loops. - Synchronous AJAX Blocking: Using
async: falsefreezes 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 theNametext exactly ensures we only target theManagerproperty. - Cleaned User Input: Trimming and filtering empty entries prevents unnecessary API calls for invalid user strings.
内容的提问来源于stack exchange,提问作者kashy
相关产品推荐
相关产品推荐

