如何从.JSON javascript中检索数据

问题描述 投票:-1回答:1

[我正在尝试从.JSON文件获取数据并导入内部HTML,但在显示“ data.forEach(function(user)不是函数”)的情况下,一直给我一个错误。

下面我的代码:

<!DOCTYPE html>
<html>
<head>
    <title>personen</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

</head>
<body>
    <button id="button_get_all_persons">get all persons</button><br/><br/>
    <button id="button_get_person">get person</button>id: <input type="text" id="txt_id"/><br/><br/>
    <button id="button_post_person">post</button> name: <input type="text" id="txt_name"/><br/><br/>

    <hr>

    <div id="output"></div>

    <script>

        document.getElementById('button_get_all_persons').addEventListener
        ('click',getUsers);

function getUsers(){
              fetch('persons.json')
              .then((res) => res.json())
              .then((data) =>{
                  let output = '<h2>Users</h2>';
                  data.forEach(function(user){
                      output += `
                        <ul class="list-group mb-3">
                        <li class="list-group-item">ID: ${user.id}</li>
                        <li class="list-group-item">Name: ${user.name}</li>
                        </ul>
                      `;
                  });
                  document.getElementById('output').innerHTML = output;
              }) 
          }
   </script>
</body>
</html>

这是我的.JSON文件

{
  "persons": [
    {
      "id": 1,
      "name": "jan"
    },
    {
      "id": 2,
      "name": "tim"
    },
    {
      "id": 3,
      "name": "ali"
    },
    {
      "name": "dirk",
      "id": 4
    }
  ]
}

有人可以向我解释情况吗,我是JS新手。先感谢您 !

javascript fetch
1个回答
1
投票

forEach是在[[arrays上找到的方法。

data不是数组,它是一个普通对象。

[data.persons是一个数组,并且确实具有forEach方法。

© www.soinside.com 2019 - 2024. All rights reserved.