【发布时间】:2019-08-16 01:16:20
【问题描述】:
我想在 javascript 中加载 json 文件。 我在下面找到了一个链接。 http://www.askyb.com/javascript/load-json-file-locally-by-js-without-jquery/
test1.json
data = '[{"name" : "Harry","age": 32.12}]';
test2.json
data = '[
{
"name" : "Harry",
"age": "32"
}
]';
上面链接中的代码适用于 test1.json,但适用于 test2.json, 我在下面遇到错误。
Uncaught SyntaxError: Invalid or unexpected token
Uncaught ReferenceError: data is not defined
at load (myscript.js:2)
at onload (test.html:8)
什么原因?
myscript.js
function load() {
var mydata = JSON.parse(data);
alert(mydata[0].name);
}
index.html
<!doctype html>
<html>
<head>
<title>Load JSON</title>
<script type="text/javascript" src="test1.json"></script>
<script type="text/javascript" src="myscript.js"></script>
</head>
<body onload="load()">
</body>
</html>
【问题讨论】:
-
你试过什么?你能显示你正在使用的代码吗?
-
我添加了代码。
-
那些标为
.json的东西,其实不是JSON文件。 -
那么,为什么它可以与 test1.json 一起工作? test1.json != test2.json?
-
您的文件是 JavaScript 文件,应命名为
test1.js/test2.js。根据您的浏览器/服务器 mime 类型的严格程度,您可能无法让浏览器将.json文件解释为 JavaScript
标签: javascript json reactjs