【发布时间】:2021-03-08 22:01:34
【问题描述】:
https://github.com/smelukov/loftschool-example 我正在这个环境中创建我的项目。
我在根文件夹中创建了 friends.json 文件。
friends.json
{
"name": "Иван",
"lastName": "Петров",
"value": "5.24"
},
{
"name": "Иван",
"lastName": "Петров",
"value": "6.00"
},
{
"name": "Иван",
"lastName": "Петров",
"value": "4.54"
}
]
index.hbs
<div id="prev-results"></div>
<button id="loadButton">Load Results</button>
index.js
const loadButton = document.querySelector("#loadButton");
const result = document.querySelector('#prev-results');
loadButton.addEventListener('click', () => {
fetch('friends.json')
.then(response => {
if (response.status >= 400){
return Promise.reject();
}
return response.json();
})
.then(friends => {
result.innerHTML = '';
for (let friend of friends) {
const friendNode = createFriendNode(friend);
result.appendChild(friendNode);
}
})
.catch(() => console.error('Что-то пошло не так'));
});
function createFriendNode(friend) {
const div = document.createElement('div');
div.classList.add('friend');
div.textContent = `${friend.name} ${friend.lastName}`;
const result = document.createElement("a");
result.textContent = `${friend.value}`;
result.classList.add("result");
const label = document.createElement("a");
label.classList.add("result-label")
label.textContent = "mL/min/1.73m²";
div.appendChild(result);
div.appendChild(label);
return div;
}
现在我可以从 friends.json 获取对象并将它们添加到 DOM 中,但是如何使用 javascript 更改 friends.json 呢?
【问题讨论】:
-
这能回答你的问题吗? Updating a JSON object using Javascript
-
在某种程度上,谢谢!
标签: javascript json fetch