我正在尝试使用Wikipedia的api和fetch。
const endpoint = 'https://en.wikipedia.org/w/api.php?
action=query&format=json&origin=*&titles=Albert%20Einstein'
fetch(endpoint)
.then(blob => blob.json())
.then(data => console.log(data))
退货
由于那个736
,我不知道如何深入研究这个问题。我假设那里什么都没有?这些结果意味着什么?
我做了这些循环,看看他们是否允许我点击控制台无法获得的东西。它与上面的提取调用相同,因此不太有用。只是想表明我至少尝试过一些东西(downvote control)。
fetch(endpoint)
.then(blob => blob.json())
.then((data) => {
for(var i in data){
//returns batch complete ,
//& query
for(var j in data.query){
//returns pages
for(var k in data.query.pages){
//returns the string 736
}
}
}
})
只需单击上面的控制台结果即可。
使用formatversion=2
获得更舒适的格式(data.query.pages
是一个数组)。
或者,您可以使用类似的东西迭代对象
var pages = data.query.pages;
for (pageId in pages) {
if (pages.hasOwnProperty(pageId)) {
console.log(pages[pageId]);
}
}
在现代浏览器中,您还可以使用Object.values()
来获取数组中对象的属性。