如何用JavaScript从用户信息列表通过用户名获取User ID及SharePoint相关问题
Hey there! Let's break down your questions and walk through practical solutions for each one:
You can use SharePoint's REST API to directly query the User Information List and filter by the target username. Here's a hands-on example:
First, construct the API endpoint targeting the User Information List (its internal name is
User Information List):const siteUrl = _spPageContextInfo.siteAbsoluteUrl; const targetUsername = "domain\\username"; // Replace with your actual username (format matches SharePoint's stored value) const apiEndpoint = `${siteUrl}/_api/web/lists/getbytitle('User Information List')/items?$select=ID,UserName&$filter=UserName eq '${targetUsername}'`;Then, send a GET request to fetch the user's details and extract the ID:
fetch(apiEndpoint, { headers: { "Accept": "application/json;odata=verbose" } }) .then(response => response.json()) .then(data => { if (data.d.results.length > 0) { const userId = data.d.results[0].ID; console.log("Found User ID:", userId); // Use this ID for your follow-up operations } else { console.log("User not found in the User Information List"); } }) .catch(error => console.error("Error retrieving User ID:", error));
Note: Ensure the username matches exactly how it's stored in SharePoint (usually domain\username or user@domain.com depending on your environment).
Since you've already added the person to the User Information List but don't have their ID, here are two reliable approaches to wrap up the process:
Option 1: Fetch the User ID immediately after adding to the User Information List
If you used the REST API to add the user, the POST response will include the full details of the created item—including the ID. Here's how to leverage that:
const siteUrl = _spPageContextInfo.siteAbsoluteUrl; // Step 1: Add user to User Information List function addToUserInfoList(userDetails) { const addUserEndpoint = `${siteUrl}/_api/web/lists/getbytitle('User Information List')/items`; const payload = { __metadata: { type: "SP.Data.User_x0020_Information_x0020_ListItem" }, Title: userDetails.preferredName, UserName: userDetails.username }; return fetch(addUserEndpoint, { method: "POST", headers: { "Accept": "application/json;odata=verbose", "Content-Type": "application/json;odata=verbose", "X-RequestDigest": $("#__REQUESTDIGEST").val() }, body: JSON.stringify(payload) }) .then(response => response.json()); } // Step 2: Use the returned User ID to add to custom list function addToCustomList(userId) { const customListEndpoint = `${siteUrl}/_api/web/lists/getbytitle('Your Custom List')/items`; const customPayload = { __metadata: { type: "SP.Data.Your_x0020_Custom_x0020_ListItem" }, // Replace 'AssignedToId' with your custom list's user field internal name AssignedToId: userId }; return fetch(customListEndpoint, { method: "POST", headers: { "Accept": "application/json;odata=verbose", "Content-Type": "application/json;odata=verbose", "X-RequestDigest": $("#__REQUESTDIGEST").val() }, body: JSON.stringify(customPayload) }); } // Execute the workflow addToUserInfoList({ preferredName: "John Doe", username: "contoso\\johndoe" }) .then(createdUser => { const userId = createdUser.d.ID; console.log("New User ID:", userId); return addToCustomList(userId); }) .then(() => console.log("Successfully added user to custom list")) .catch(error => console.error("Operation failed:", error));
Option 2: Retrieve the User ID using Preferred Name/Username
If you don't have the initial add operation's response, use the method from Question 1 to fetch the ID. You can even filter by the Preferred Name (stored in the Title field of the User Information List) if that's what you have:
const preferredName = "John Doe"; const apiEndpoint = `${siteUrl}/_api/web/lists/getbytitle('User Information List')/items?$select=ID&$filter=Title eq '${preferredName}'`;
Pro Tip: Using UserName is more reliable than Preferred Name, as multiple users might share the same display name.
内容的提问来源于stack exchange,提问作者Avinash chowdary

