如何在 html 中显示获取的数据

How to display fetched data in html

我正在获取待办事项列表,我想知道为什么在我这样做时它会给我 undefined

.then((response) => {
  response.json();
  }

适用于

.then(response => response.json())

为什么会这样?

此外,当我获取数据时,它们是对象,我将它们保存在数组中

  completed: true,
  id: 199,
  title: "numquam repellendus a magnam",
  userId: 10
},

等..

现在,我有 html 模板,我想将它加载到我的 html 我的样式所在的位置,我该怎么做?

<div class="card">
<p>//Want Id here</p>
<strong>// Want Title here</strong>
</div>

获取代码:

let todos = [];

function fetchData() {
    fetch('https://jsonplaceholder.typicode.com/todos').then(response => response.json())
  .then((json) => {
    todos = json;
    console.log(todos);
  })
  }

fetchData();
.then((response) => {
  response.json();
})

上面的这个函数没有 return 任何东西。它 response.json() 但不 return 它。

您需要添加 return 以便它传递给下一个 .then() :

.then((response) => {
  return response.json();
})

这行得通。但是 ES6 允许一个很好的语法糖:

.then(response => response.json())

如果没有大括号,response.json() 将被 return 编辑,而您不必显式地写 return.

这就是有牙套和没有牙套的区别

但是有一个更好的方法来处理它,使用 async/await :

let todos = [];

async function fetchData() {
    const response = await fetch('https://jsonplaceholder.typicode.com/todos');
    const todos = await response.json();
    console.log(todos);
}

fetchData();

你为什么不使用 template literals

我的建议:

let todos = [];

fetchData();

function fetchData() {
  fetch('https://jsonplaceholder.typicode.com/todos')
    .then(response => response.json())
    .then(json => todos = json)
    .then(() => {
      for (let item of todos) {
        toAppend.innerHTML += `
<div class="card">
<p>${item.id}</p>
<h2>${item.title}</h2>
</div>
`;
      }
    });
}
<div id="toAppend"></div>

无论如何,如果您只需要显示获取的项目,另一种更简单的解决方案可以是:

const fetchData = async() => (await fetch('https://jsonplaceholder.typicode.com/todos')).json();

fetchData()
  .then(data => {
    for (let item of data) {
      toAppend.innerHTML += `
<div class="card">
<p>${item.id}</p>
<h2>${item.title}</h2>
</div>
`;
    }
  });
<div id="toAppend"></div>

这里fetchData()是一个asynchronous function.