首页 > 解决方案 > 从json文件读取时无法将未定义转换为对象

问题描述

场景

问题can't convert undefined to object在 mozilla firefox 中加载没有断点的 html 时出现问题。

代码:我有一个节点项目,我开始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 的顺序有关。但我不是这些方面的专家,因此非常感谢任何帮助。

让我知道是否需要任何进一步的信息。

标签: javascripthtmlnode.jsjsonhighcharts

解决方案


推荐阅读