繁体   English   中英

如何在 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
},

ETC..

现在,我有 html 模板,我想将它加载到我的 html 中,我的 styles 是,我该怎么做?

<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();
})

上面的这个 function 不返回任何东西。 它执行response.json()但不返回它。

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

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

这将起作用。 但是 ES6 允许一个很好的语法糖:

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

没有大括号, response.json()将被返回,而您不必显式编写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();

为什么不使用模板文字

我的建议:

 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()是一个异步 function

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM