[英]When importing a .json file into javascript my HTML file loses the ability to call functions from the javascript code
嘿,这真的很奇怪。
我将在这里给出一些代码示例:
HTML:
<body style="background-color:rgb(157, 163, 163)" onload="createData()">
<script src="indexLIS.js"></script>
<script src="assets/initData.json"></script>
</body>
Javascript:
//import dataSource from './assets/initData.json';
function createData(){
console.log("hey");
}
JSON:
{
"dataSource":[
{
"id": 0,
"name":"TemporaryName",
"node-level":0
}
]
}
在一个即使如此简单的代码示例中,每次我打开 HTML 时,我几乎都会立即将“嘿”打印到控制台。 However, if I uncomment the first line of the javascript code there and import the data from initData.json, then I immediately get the error "createData not defined" as though the HTML code has completely lost the ability to communicate with the javascript file.
编辑:我刚刚意识到你在上面使用 es6 模块语法(它读起来就像我的代码注释)。 您可能想查看这个问题: 如何在 ecmascript 6 中导入 json 文件?
原始答案:
您不能在script
标签中加载json
。 当你这样做时,浏览器无法解析它,这会杀死页面上的所有脚本执行。
如果您将initData.json
文件更改为initData.js
:
var jsonData = {
"dataSource":[
{
"id": 0,
"name":"TemporaryName",
"node-level":0
}
]
};
然后,您应该能够从全局jsonData
变量中引用数据。
我最终能够让它为我工作。 我不能确定这是否是最适合每个人的答案,但它完成了我打算做的事情。
HTML:
<body style="background-color:rgb(157, 163, 163)" onload="createData()">
<script type="text/javascript" src="indexLIS.js"></script>
</body>
Javascript:
function createData() {
$.getJSON('./assets/initData.json', function(json) {
console.log(json.dataSource);
});
}
Nothing changed in the Json itself, so I wont post that, but this way I was able to import the JSON data and interact with it without killing the relationship between the javascript file and the html. 必须在function(json){}
部分中使用 json 做所有你想做的事情似乎是有限的,但我在那里所做的只是将json
发送到另一个 ZC1C425268E68385D1AB5074C17A9,所以它真的很慢14完全下降。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.