2017-04-19 75 views
0

我遇到了麻烦json文件的问题,我现在没有问题在哪里,希望你能帮助我。加载本地json文件并将结果分配给变量

<script type="text/javascript"> 
var d; 
$.getJSON("empl-estab.json", function (data) { 
d=data; 
}); 
console.log(d); 
var chart = Highcharts.chart('container', { 
title: { 
         text: 'Statistiques' 
        }, 
        subtitle: { 
         text: 'Plan' 
        }, 
        xAxis: { 
         categories: d.categories, 
        }, 
        series: [{ 
          type: 'column', 
          colorByPoint: true, 
          data: d.data, 
          showInLegend: false 
         }] 

       }); 
</script> 

误差为:d是未定义

+1

所有代码依赖于'D'必须是你'.getJSON'成功函数内。你知道......哪里有'd = data'。所以......是的,你也需要把HighCharts放在那里。 – PHPglue

+0

我解决它,就像@Mamun说的,我应该把所有的代码移动到$ .getJSON,我有一个文件位置的问题,谢谢你们,你们都很棒。 – rafik

回答

1

将所有有关的内部getJSONcallback功能response结果的代码。发生这种情况是因为在请求完成之前,所有外部代码都正在执行。因此d未定义。

var d; 
$.getJSON("empl-estab.json", function (data) { 
    d=data; 
    console.log(d); 
    var chart = Highcharts.chart('container', { 
    title: { 
     text: 'Statistiques' 
    }, 
    subtitle: { 
     text: 'Plan' 
    }, 
    xAxis: { 
     categories: d.categories, 
    }, 
    series: [{ 
      type: 'column', 
      colorByPoint: true, 
      data: d.data, 
      showInLegend: false 
     }] 

    }); 
}); 
1

这是由于GET请求的异步性质。你写的代码在GET请求返回之前执行console.log语句。您希望将逻辑放置在返回文档后执行的回调函数中。

0

而且,async function里面的变量可以等待下载没有问题:

async function load() { 
    //The await keyword will make the d variable wait for the json file 
    var d = await fetch('empl-estab.json').then(file => file.json()); 

    //Now your d variable is avaliable 
    console.log(d);  
} 
load(); 
相关问题