javascript - 如何在 JavaScript 对象中存储 Fetch API JSON 响应
问题描述
我想将 Fetch API JSON 存储为 JavaScript 对象,以便在其他地方使用它。console.log 测试有效,但我无法访问数据。
以下作品:它显示了带有三个待办事项的控制台条目:
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));
如果我尝试访问成功,它不包含任何数据。
试过console.log,它有效。
还尝试了以下方法,这些方法有效:
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。
解决方案
您还可以使用如下函数:
function doSomething(success){
//do whatever you like
}
fetch('http://localhost:3000/api/todos')
.then(data => data.json())
.then(success => doSomething(success));
推荐阅读
- python - 在网页抓取期间,我收到以下错误“无效语法(
,第 11 行)”在 python 3.4.4 中写入 print commad - hadoop - 在不同的用户上使用 Sqoop?
- c# - 特殊字符之前的单词边界匹配失败
- mysql - 如何更新时间戳
- spring-boot - Gradle java.lang.OutOfMemoryError:元空间
- caching - 构造唯一性由 6 个属性定义的缓存键的最佳方法
- laravel - 条件不适用于条件
- prolog - 用于检查列表中的变量名的内置谓词
- linux - 在 Dockerfile 中按回车
- vba - Excel 到 PDF 转换的宏