1

我有一个奇怪的错误。当我尝试运行我的代码时:

var firstJson;
$.getJSON(site_url+"/more/sector_by_city/"+id+"?"+Math.random(), function( json ) { 
    $.each(json, function(key, value) {
        firstJson = 9;  
    });
}); 
alert(firstJson);

我得到的警报是:"undefined"

为什么我得到这个而不是得到9

我在这里想念什么?

(每个循环运行没有问题,并且 JSON 中有值)最后,9更改为其他值。

谢谢

4

3 回答 3

6

异步函数我的朋友。.getJSON您的警报在您的请求完成之前被调用。您需要使用回调函数来获得正确的警报。

于 2013-06-25T15:28:43.030 回答
4

因为当你调用alert(firstJson)的时候异步$.getJSON调用还没有完成,所以firstJson没有与之关联的值。如果您将警报移动到$.each函数中或在$.each, 和末尾$.getJSON,它将有一个值。

于 2013-06-25T15:29:25.050 回答
2

alert调用时变量没有值。您必须等待getJSON结束,使用done().

var firstJson;
$.getJSON(site_url+"/more/sector_by_city/"+id+"?"+Math.random(), function( json ) { 
    $.each(json, function(key, value) {
        firstJson = 9;  
    });
}).done(function() {
   alert(firstJson);
});

参考:

  1. done()
  2. $.getJSON
于 2013-06-25T15:32:55.750 回答