将jQuery getJSON中的数据分配给数组

ina*_*ina 4 jquery getjson

如何将获取的数据分配getJSON()给一个数组,供以后使用?

下面的getJSON url检索具有10个主要元素的格式正确的JSON,每个元素都包含id,username,haiku(和其他)的子元素.如果您正在运行它,请尝试将JSON元素保存到本地文件,这样您就不会得到相同的域错误(即,如果您从其他域获取,则不会加载JSON).

发生的情况是警报将在getJSON回调中获取值,但在外部,该值未定义.


$(document).ready(function(){
    var haikus=[];
    alert("begin loop");
    $.getJSON('http://example.com/json.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)];
        }
            alert(haikus[0][1]);
    });
})

  • 是的,这与之前的帖子有关.但是,我最初简化了我的问题,所以提供的初始解决方案并没有解决它.jQuery - getJSON数据到数组

use*_*716 19

您的问题是,在收到响应之前,请求之外(和之后)的任何代码$.getJSON都已运行$.getJSON.

请记住,AJAX调用是异步的.这意味着AJAX请求之后的代码不会等待响应执行.所以它在有任何回应之前很久就会运行.

关键是任何依赖于异步AJAX请求响应的代码都必须在回调中运行(或从中调用).


编辑:

为了澄清,在下面的代码示例中,请参阅代码注释.它应该有助于解释这个问题.

$(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]);

});
Run Code Online (Sandbox Code Playgroud)

  • @ina - 是的,当然.请参阅此示例:http://jsfiddle.net/FgV8W/如果在加载JSON时单击该值,则无法获取任何内容,如果在完成后单击它,它将为您提供数据. (2认同)