我对 .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
给出两个不同的答案,即使它们都引用同一个变量?一个未定义,另一个工作正常。
我编辑了问题,使其仅反射(reflect)面临的问题。
最佳答案
你不能要求 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 ready
关于JavaScript、Jquery 代码笔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41924168/