我正在编写一个 JavaScipt 应用程序,并尝试从某个 URL 获取数据,但得到一个未定义的值。获取并将其转换为 json 后的预期值应生成一个数组。我不知道为什么会发生这种情况。我已将代码放在下面:
let promiseResponse = fetch("some-url");
let response = await promiseResponse;
// check if there was an error in fetching the data (no error detected)
if(!response.ok) {
alert("An error occured when attempting to fetch data.")
}
// a console.log statement here for the var 'response' results in "[object Promise]"
let parsedPromiseResonse = response.json();
let parsedResponse = await parsedPromiseResonse;
// printing out the 'parsedResponse' var gives me [object Object]
// printing out the 'parsedResponse[0]' var gives me undefined
编辑: 为了了解更多上下文,要在 URL 中检索的数据的格式如下:
{"variants":["some-string","some-string"]}
任何帮助将不胜感激!
最佳答案
要访问 json,必须调用实体变体,然后访问项目,例如
alert(parsedResponse.variants[0])
结果应该是
some-string
关于javascript - fetch 解析 json 后返回 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61200796/