Saving fetched JSON into variable(将获取的 JSON 保存到变量中)
问题描述
我正在尝试将 JSON 保存到一个变量中,但似乎我不明白这里的所有内容.我让 JSON 以我喜欢的方式出现在控制台中,但是在我稍后再次尝试调用它之后,它只返回承诺.如何将 JSON 保存到变量中,以便以后使用 JSON 中的对象?
I'm trying to get JSON saved into a variable, but it seems I don't understand everything here. I get JSON show up in console a once the way I like, but after I try to call it again later it only returns promise. How can I get JSON saved into a variable, so I could use objects in JSON later?
var jsondata = fetch(url).then(
function(u){ return u.json();}
).then(
function(json){
console.log(json);
}
)
console.log(jsondata);
推荐答案
let jsondata;
fetch(url).then(
function(u){ return u.json();}
).then(
function(json){
jsondata = json;
}
)
基本上,一旦 Promise 使用实际数据解析,您需要分配您的 jsondata
变量.目前,您将整个承诺分配给您的 jsondata
变量,这不是您想要的.
Basically you need to assign your jsondata
variable once the promise resolves with the actual data. Currently, you're assigning the entire promise to your jsondata
variable which is not what you want.
这篇关于将获取的 JSON 保存到变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将获取的 JSON 保存到变量中


- 400或500级别的HTTP响应 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07