如何在JavaScript对象中存储Fetch API JSON响应 [英] How to Store Fetch API JSON Response in a JavaScript Object
本文介绍了如何在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;我需要该对象来执行其他UX.
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));
这篇关于如何在JavaScript对象中存储Fetch API JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文