JavaScript-来自Ajax的对象迭代

发布于 2025-02-14 01:55:46 字数 593 浏览 4 评论 0原文

我正在学习JavaScript,今天我学习了Ajax。 我正在使用香草JS和简单的Ajax。 我的任务是通过用户输入-ID从URL获取用户的对象。 我尝试了.data,但仍然无法使用。 任何帮助都将被应用!

async function display() {
  try {
    let id = +userID.value;
    const url = `https://jsonplaceholder.typicode.com/users/${id}`;
    const response = await fetch(url);
    const rootObject = await response.json();
    const users = rootObject.data;
    getUser(users);
  } catch (err) {
    alert(err.message);
  }
}

display()

我有另一个功能 - 当前是空的getusers(用户),因为它不起作用。 如何仅从URL访问对象?

I'm learning Javascript and today I learned AJAX.
I am using Vanilla JS and simple AJAX.
My task is to get the object of a user from the url by user input - ID.
I've tried the .data and still won't work.
Any help would be appriciated!

async function display() {
  try {
    let id = +userID.value;
    const url = `https://jsonplaceholder.typicode.com/users/${id}`;
    const response = await fetch(url);
    const rootObject = await response.json();
    const users = rootObject.data;
    getUser(users);
  } catch (err) {
    alert(err.message);
  }
}

display()

I have another function - getusers(users) that currently is empty because it isn't working.
How can I access the object only from the url?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

装纯掩盖桑 2025-02-21 01:55:46

返回的JSON中没有数据属性。只需解析JSON,然后将该数据作为参数GetUser

function getUser(data) {
  for (const prop in data) {
    console.log(`${prop}: ${data[prop]}`);
  }
}

async function display(id) {
  try {
    const url = `https://jsonplaceholder.typicode.com/users/${id}`;
    const response = await fetch(url);
    const data = await response.json();
    getUser(data);
  } catch (err) {
    console.log(err.message);
  }
}

display(3);

There is no data property in the returned JSON. Just parse the JSON and then have that data as an argument to getUser.

function getUser(data) {
  for (const prop in data) {
    console.log(`${prop}: ${data[prop]}`);
  }
}

async function display(id) {
  try {
    const url = `https://jsonplaceholder.typicode.com/users/${id}`;
    const response = await fetch(url);
    const data = await response.json();
    getUser(data);
  } catch (err) {
    console.log(err.message);
  }
}

display(3);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文