使用原生JavaScript(Vanilla JS)通过AJAX根据用户输入ID获取用户对象的问题求助
Hey there! I see where the problem is—let's get this sorted out for you.
The Core Issue
The API you're using (https://jsonplaceholder.typicode.com/users/${id}) returns a single user object directly, not wrapped inside a data property. When you try to access rootObject.data, you're looking for a property that doesn't exist, which is why your code isn't working.
Corrected Code
Here's how to adjust your display function to get the user data correctly:
async function display() { try { let id = +userID.value; const url = `https://jsonplaceholder.typicode.com/users/${id}`; const response = await fetch(url); // Add a check for successful response status if (!response.ok) { throw new Error(`User with ID ${id} not found`); } const user = await response.json(); // This is the direct user object getUser(user); // Pass the full user object to your function } catch (err) { alert(err.message); } } display();
Example getUser Function
Since your getUser function was empty, here's a simple example to render the user data (tweak this to match your specific needs):
function getUser(user) { // Log user details to console for debugging console.log("Fetched User:", user); // Or render data to the DOM, e.g.: const userCard = document.getElementById('user-card'); userCard.innerHTML = ` <h2>${user.name}</h2> <p><strong>Username:</strong> ${user.username}</p> <p><strong>Email:</strong> ${user.email}</p> <p><strong>Phone:</strong> ${user.phone}</p> <p><strong>City:</strong> ${user.address.city}</p> `; }
Pro Tip for Future Debugging
If you're ever unsure about an API's response structure, add console.log(rootObject) right after parsing the JSON. This will show you exactly what data you're working with in your browser's dev tools, so you can avoid guessing at property names.
内容的提问来源于stack exchange,提问作者DennisR93

