我快被.getjson迷住了。我正在尝试使用.getjson从Wikipedia API获取数据,它工作得很好。假设Wikipedia API返回10个选择,在循环每个选择之前,我尝试在for循环中查找数组的长度。“.getjson”中的数据尚不可用。
Here是我在codepen中的工作。看看for循环中的console.log(sp.length);和sp.length。他们应该给出类似的数据,但其中一个是未定义的,另一个工作正常。
下面是我的JS代码:
$( document ).ready(function() {
var api_wiki="https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&titles=Main+Page&srsearch=cat&srwhat=text&callback=?";
var sp;
$.getJSON(api_wiki,function(data){
sp=data.query.search;
// console.log(sp.length);
}); //End of getJSON
for (var i=0;i<sp.length;i++){
}
});//End of get ready为什么console.log给出了两个不同的答案,尽管它们都引用了同一个变量?一个是未定义的,另一个工作正常。我对问题进行了编辑,使其只反映所面临的问题。
发布于 2017-01-31 01:58:02
你不能要求javascript使用它还没有的数据。您需要等待数据到达。尝试将for循环放在函数中,并在getJSON的onReady事件中调用该函数:
$( document ).ready(function() {
var api_wiki="https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&titles=Main+Page&srsearch=cat&srwhat=text&callback=?";
var sp;
$.getJSON(api_wiki,function(data){
sp=data.query.search;
console.log(sp.length);
workWithTheData(sp);
}); //End of getJSON
function workWithTheData(sp){
for (var i=0;i<sp.length;i++){
console.log(sp[i]);
}
}
});//End of get readyhttps://stackoverflow.com/questions/41924168
复制相似问题