Javascript 无法从API调用检索特定的JSON数据
我试图使用变量“myResult”返回特定的JSON数据。我相信我可能把“myResult”变量写错了,我没有查询正确的数据。Javascript 无法从API调用检索特定的JSON数据,javascript,json,api,fetch,Javascript,Json,Api,Fetch,我试图使用变量“myResult”返回特定的JSON数据。我相信我可能把“myResult”变量写错了,我没有查询正确的数据。'[1].show.score'的路径是正确的,我将添加我试图调用的JSON数据的屏幕截图。 当我调用此数据时,我收到以下错误: [![我的错误][2][2] 以下是“url”的结果 [![从变量“url”返回的JSON数据][1][1] 这是我的密码: document.querySelector('.myButton').addEventListener('click
'[1].show.score'
的路径是正确的,我将添加我试图调用的JSON数据的屏幕截图。
当我调用此数据时,我收到以下错误:
[![我的错误][2][2]
以下是“url”的结果
[![从变量“url”返回的JSON数据][1][1]
这是我的密码:
document.querySelector('.myButton').addEventListener('click', function(){
var query = document.getElementById('main').value;
var url = fetch("http://api.tvmaze.com/search/shows?q="+query)
.then(response => response.json())
.then(data => console.log(data));
var myResult = url[1].show.score;
console.log(myResult);
})```
[1]: https://i.stack.imgur.com/lTn8V.png
[2]: https://i.stack.imgur.com/kS7gB.png
您无法从
url
访问数据,您尝试使用url[1]访问数据的方式。show.score
,因为url
承诺您可以调用.then()
和.catch()
来接收数据,您已经这样做了
如果希望myResult
使用特定数据,则需要在回调中使用它
所以最后你可能会有这样的结果:
document.querySelector('.myButton').addEventListener('click', function(){
var query = document.getElementById('main').value;
fetch("http://api.tvmaze.com/search/shows?q="+query)
.then(response => response.json())
.then(data => {
console.log(data));
var myResult = data[1].show.score;
console.log(myResult);
}
})
这回答了你的问题吗?