从json文件读取时获取无法将undefined转换为对象

时间:2019-05-26 20:11:00

标签: javascript html node.js json highcharts

场景

  • 一个json文件
  • 使用highcharts读取json数据并绘制图形

问题:在mozilla firefox中加载无断点的html时获取can't convert undefined to object

  • 在加载带有断点的图形时,图形会得到完美绘制。
  • 没有断点,将myjson设为函数chartFormyJson中的未定义

代码: 我有一个节点项目,并且正在使用http server开始npm run serve

Index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://code.highcharts.com/highcharts.js"></script>
    <script src="scriptFile.js"></script>
</head>
<body>
<div id="container" style="width:100%; height:400px;"></div>
</body>
</html>

scriptFile.js

var myjson;
fetch('./data.json').then(response => response.json()).then(data => {
    myjson=data["myjson"];
})

if( document.readyState !== 'loading' ) {
    console.log( 'document is already ready, just execute code here' );
    chartFormyJson();
} else {
    document.addEventListener('DOMContentLoaded', function () {
        console.log( 'document was not ready, place code here' );
        chartFormyJson();
    });
}

function chartFormyJson(){
var myChart = Highcharts.chart('container', {
    chart: {
        type: 'column'
    },
    title: {
        text: 'Plot bar graph per year'
    },
    yAxis: {
        title: {
            text: 'Count'
        }
    },
    xAxis: {
        categories: Object.keys(myjson)
    },
    series: [{
        data: Object.values(myjson)
    }]
});
}

需要这种方式的指导。似乎与从html加载数据/变量/调用js有关。但是我不是专家,因此,我们将不胜感激。

让我知道是否需要其他信息。

0 个答案:

没有答案