weixin_33724570 2017-01-29 18:02 采纳率: 0%
浏览 30

Javascript,jQuery Codepen

I am going crazy with .getjson. I am trying to get data from a Wikipedia API using .getjson and it works fine. Let's say the Wikipedia API returns 10 selections, and before looping over each selection, I am trying to find the length of array in a for loop. The data is not available yet from the '.getjson'.

Here is my work in codepen. Look at console.log(sp.length); and sp.length in the for loop. They should give similar data, but one of them is undefined and other is working fine.

Here is my JS code:

    $( 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

Why does console.log give two different answers even though they both refer to the same variable? One is undefined and the other is working fine. I edited the question so that it only reflect the problem facing.

  • 写回答

1条回答 默认 最新

  • weixin_33727510 2017-01-30 17:58
    关注

    You can't ask javascript to use data it doesn't have yet. You need to wait for the data to arrive. Try putting the for loop inside a function and calling the function in the onReady event of the getJSON:

    $( 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
    
    评论

报告相同问题?