[英]how to retrieve data from .JSON javascript
我正在嘗試從 .JSON 文件中獲取數據並導入內部 HTML,但它一直給我一個錯誤,上面寫着“data.forEach(function(user) is not a function”
我的代碼如下:
<!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 新手。 先感謝您 !
forEach
是一種在數組上找到的方法。
data
不是數組,它是一個普通對象。
data.persons
是一個數組,並且有一個forEach
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.