如何在 JavaScript 对象中存储 Fetch API JSON 响应
问题描述:
我想将 Fetch API JSON 存储为 JavaScript 对象,以便我可以在其他地方使用它.console.log 测试有效,但我无法访问数据.
I want to store a Fetch API JSON as a JavaScript object, so I can use it elsewhere. The console.log test works, but I can't access the data.
以下工作:它显示了包含三个待办事项的控制台条目:
The Following Works: It shows console entries with three to-do items:
fetch('http://localhost:3000/api/todos')
.then(data => data.json())
.then(success => console.log(success));
以下不起作用:
fetch('http://localhost:3000/api/todos')
.then(data => data.json())
.then(success => JSON.parse(success));
如果我尝试访问成功,它不包含任何数据.
If I try to access success, it does not contain any data.
已经尝试过 console.log,它有效.
Have tried console.log, which works.
也尝试了以下方法,效果很好:
Have also tried the following, which works:
fetch('http://localhost:3000/api/todos')
.then(res => res.json())
.then(data => {
let output = '';
data.forEach(function (todo) {
output += `
<ul>
<li>ID: ${todo.id}</li>
<li>Title: ${todo.title}</li>
<li>IsDone: ${todo.isdone}</li>
</ul>
`;
});
document.getElementById('ToDoList').innerHTML = output;
return output;
})
.catch(err => console.log('Something went wrong: ', err));
但是,我无法手动更新内部 HTML;我需要这个对象来做其他用户体验.
However, I can't manually update inner HTML; I need the object to do other UX.
答
您也可以使用如下函数:
You can also use a function like below:
function doSomething(success){
//do whatever you like
}
fetch('http://localhost:3000/api/todos')
.then(data => data.json())
.then(success => doSomething(success));