Assign data from jQuery getJSON to array

风流意气都作罢 提交于 2019-11-29 00:31:27

Your issue is that any code outside (and after) the $.getJSON request has already run by the time the $.getJSON response is received.

Remember that AJAX calls are asynchronous. This means that the code following the AJAX request does not wait for the response to execute. So it runs long before there's any response.

The key is that any code that relies on the response from an asynchronous AJAX request, must run (or be called from) inside the callback.


EDIT:

To clarify, in the code example below, please see the code comments. It should help explain the issue.

$(document).ready(function(){
    var haikus=[];
    alert("begin loop");
    $.getJSON('http://haikuennui.com/random.php',function(data){
         var i=0;
         for(i=0;i<data.length;i++){
            haikus[i]=[data[i].id,String(data[i].username),String(data[i].haiku)];
        }
                 // The data in haikus is available here becuase
                 //    this alert() doesn't run until the response is received.
            alert(haikus[0][1]);
    });

         // Here the data in haikus is NOT available because this line
         //     of code will run ***before*** the response from the AJAX
         //     request from above is received.
         // In other words, this alert() executes **immediately** without
         //     waiting for the $.getJSON() to receive its response.
    alert(haikus[0][1]);

});

I believe if you define a variable by using 'var haikus = something', the variable is of local scope, and if you define the variable by using 'haikus = something', it is of global scope.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!