如何在html中显示获取的数据 [英] How to display fetched data in html

查看:134
本文介绍了如何在html中显示获取的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am fetching todo list, I am wondering why it gives me undefined when I do this

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

它与

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

为什么会这样?

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

Also, when I'm fetching the data, they are objects and I save them in array

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

等.

现在,我有用于此的html模板,我想将其加载到我的样式所在的html中,该怎么做?

Now, I have html template for this, I'd like to load this in my html where my styles are, how can I do this?

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

上面的此函数不返回任何内容.它会执行 response.json(),但不会返回它.

This function above doesn't return anything. It does response.json() but does not return it.

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

You need to add return so it gets passed to the next .then() :

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

这将起作用.但是ES6允许使用漂亮的语法糖:

This will work. But ES6 allows a nice syntactic sugar :

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

如果不使用大括号,将返回 response.json(),而无需显式编写 return .

Without the braces, response.json() will be returned, without you having to explicitly write return.

这是大括号和没有大括号的区别.

This is the difference between braces and no braces.

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

But there's an even nicer way to deal with it, using 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();

这篇关于如何在html中显示获取的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆