【问题标题】:How to display fetched data in html如何在html中显示获取的数据
【发布时间】:2021-03-14 15:51:10
【问题描述】:

我正在获取待办事项列表,我想知道为什么当我这样做时它会给我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();

【问题讨论】:

    标签: javascript fetch-api


    【解决方案1】:

    你为什么不用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>
    `;
          }
        });
    }
    &lt;div id="toAppend"&gt;&lt;/div&gt;

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

    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>
    `;
        }
      });
    &lt;div id="toAppend"&gt;&lt;/div&gt;

    这里的fetchData()asynchronous function

    【讨论】:

      【解决方案2】:
      .then((response) => {
        response.json();
      })
      

      上面的这个函数不返回任何东西。它会 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();
      

      【讨论】:

      • 另外,如何在 html 中显示获取的项目?我想用我的 html 中的元素显示整个数组。我需要一个单独循环的函数吗?
      • 这里到处都有基本教程。只是谷歌它。 stackoverflow.com/questions/34907982/…
      • 你能看到这个jsfiddle.net/17mhcuz8,我完全不知道为什么它没有记录循环,我也试过forEach
      • 好吧,显然是因为您试图在填充 todos 之前对其进行循环。您正在循环 [],然后 然后 数组被填充。 todos = json; loopitems();
      • 所以我需要把所有东西都移到上面的函数中吗?
      猜你喜欢
      • 1970-01-01
      • 2021-06-06
      • 1970-01-01
      • 2018-06-11
      • 2021-05-03
      • 2022-01-23
      • 2018-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多