javascript - 从json文件读取时无法将未定义转换为对象
问题描述
场景:
- 一个json文件
- 使用 highcharts 读取 json 数据并绘制图形
问题:can't convert undefined to object
在 mozilla firefox 中加载没有断点的 html 时出现问题。
- 使用断点加载时,图表会被完美绘制。
- 没有断点,
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 的顺序有关。但我不是这些方面的专家,因此非常感谢任何帮助。
让我知道是否需要任何进一步的信息。
解决方案
推荐阅读
- ruby-on-rails - Ubuntu 在后台运行 Puma 和 Sidekiq 作为守护进程
- sql - 比较 PL SQL 中同一列在 2 天内的值
- c - 将 C 中的结构与用户定义的函数一起使用
- javascript - 如何强制实现自动完成文本流到新行?
- javascript - 为 getQueryStringParams 中的变量赋值
- angular - 使用 RXJS 修改 http 响应
- c# - C# 在 Azure SQL 中使用异步或线程进行长时间运行的数据库活动
- python - Pandas - 按时间增量和计数计算连续行数
- python - 计算两个输入时间之间的时间差
- kotlin - 如何从 Kotlin 的 micronaut 应用程序中的多个表中提取 DTO?