Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 变量范围:函数内的全局变量_Javascript_Json - Fatal编程技术网

Javascript 变量范围:函数内的全局变量

Javascript 变量范围:函数内的全局变量,javascript,json,Javascript,Json,我尝试将JSON数组分配给变量,如下所示: $.getJSON("tljson.json",function(result){ items = JSON.stringify(result); }); 然后在函数外部调用该变量: timeline.draw (items,options); 在getJSON函数内部使用alert(items)可以工作,但是在函数外部,它只返回“undefined”。我认为这是可行的,因为我在getJSON函数中将items声明为全局变量。我做错了什么?这是

我尝试将JSON数组分配给变量,如下所示:

$.getJSON("tljson.json",function(result){
  items = JSON.stringify(result);
});
然后在函数外部调用该变量:

timeline.draw (items,options);

在getJSON函数内部使用alert(items)可以工作,但是在函数外部,它只返回“undefined”。我认为这是可行的,因为我在getJSON函数中将items声明为全局变量。我做错了什么?

这是因为您的代码是在收到getJSON的响应之前执行的。像这样使用它:

  function afterGetJSON(items) {
    timeline.draw (items,options);
  }

  $.getJSON("tljson.json",function(result){
    items = JSON.stringify(result);
    afterGetJSON(items);

  });

这是因为您的代码是在收到getJSON的响应之前执行的。像这样使用它:

  function afterGetJSON(items) {
    timeline.draw (items,options);
  }

  $.getJSON("tljson.json",function(result){
    items = JSON.stringify(result);
    afterGetJSON(items);

  });

您可能没有等待
getJSON
函数完成。它是异步的,这意味着它下面的代码将在回调函数中的代码之前执行

alert(1);
$.getJSON("tljson.json",function(result){
  alert(2);
  items = JSON.stringify(result);
});
alert(3);
上面的例子实际上是先警告
1
然后警告
3
然后警告
2
。请注意,
3
2
之前

为了修复代码,您需要等待回调函数被调用,以便在尝试使用该变量之前,回调函数可以为
赋值。提出解决方案可能取决于您的情况,但一个简单的想法是从回调函数中调用一些函数

$.getJSON("tljson.json",function(result){
  items = JSON.stringify(result);
  doSomethingWithItems();
});

function doSomethingWithItems() {
  alert(items); // Correctly alerts items.
}

您可能没有等待
getJSON
函数完成。它是异步的,这意味着它下面的代码将在回调函数中的代码之前执行

alert(1);
$.getJSON("tljson.json",function(result){
  alert(2);
  items = JSON.stringify(result);
});
alert(3);
上面的例子实际上是先警告
1
然后警告
3
然后警告
2
。请注意,
3
2
之前

为了修复代码,您需要等待回调函数被调用,以便在尝试使用该变量之前,回调函数可以为
赋值。提出解决方案可能取决于您的情况,但一个简单的想法是从回调函数中调用一些函数

$.getJSON("tljson.json",function(result){
  items = JSON.stringify(result);
  doSomethingWithItems();
});

function doSomethingWithItems() {
  alert(items); // Correctly alerts items.
}