【问题标题】:Loading local json file and assigning the result to a variable加载本地 json 文件并将结果分配给变量
【发布时间】:2017-09-16 09:45:42
【问题描述】:

我在解析 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 未定义

【问题讨论】:

  • 所有依赖于d 的代码必须在你的.getJSON 成功函数中。你知道...d=data 在哪里。所以...是的,你也需要把你的 HighCharts 放在那里。
  • 我解决了,就像@Mamun 说的,我应该将所有代码移动到$.getJSON,我遇到了文件位置问题,谢谢你们,你们都很棒。

标签: javascript json parsing getjson


【解决方案1】:

将与response 结果相关的所有代码放在getJSONcallback 函数中。发生这种情况是因为外部的所有代码都在请求完成之前执行。因此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
        }]

  });
});

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      另外,在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();
      

      【讨论】:

        猜你喜欢
        • 2016-04-21
        • 1970-01-01
        • 2013-01-07
        • 2022-01-06
        • 2021-02-04
        • 1970-01-01
        • 2017-04-16
        • 1970-01-01
        相关资源
        最近更新 更多