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

使用原生JavaScript(Vanilla JS)通过AJAX根据用户输入ID获取用户对象的问题求助

Fixing Your AJAX User Fetch Issue with Vanilla JS

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 20:09:06