我正在尝试学习JS,并且对JAVA的经验有限。我希望(从长期来看)开发一个Web应用程序,以帮助我的学生进行物理入门课。在创建此应用程序的第一步中,我将一些基本方程式(如TeX格式的字符串,以后将以舒适的格式显示为方程式)和数据存储在与html文件相同的文件夹中的.json文件中,该文件将调用我的.js文件来执行一些功能。
我已经搜索了一些有关如何在javascript中上载/读取json文件的信息,但是大多数文章似乎都在讨论使用AJAX或jquery(我不熟悉这些内容,并且$ .function()调用使我感到困惑)。从js是服务器端和json数据是客户端的意义上讲,大多数其他对象都适合加载本地文件。谁能指出我对我的应用程序有用的代码的方向?我想将方程数据保存在一个单独的文件中,以使其易于修改,并且我计划为应用提供类似的json格式数据,以导入一系列可选的物理概念。
JSON数据的示例如下所示,并存储在名为“ equations.json”的同一文件夹中的文件中
{
"equationGroup": [{
"equationGroupName": "Kinematics",
"equation": [{
"equationName": "Final Velocity Squared",
"equationTeX": "v_{f}^{2}=v_{i}^{2}+2a(x-x_{0})",
"equationVariables": [{
"variableTeX": "v_{f}",
"variableDescription": "The final velocity"
},
{
"variableTeX": "v_{0}",
"variableDescription": "The starting velocity"
},
{
"variableTeX": "a",
"variableDescription": "Acceleration in the same plane as velocity\""
},
{
"variableTeX": "x",
"variableDescription": "The final displacement"
},
{
"variableTeX": "x_{0}",
"variableDescription": "The starting point (initial displacement)"
}
]
},
{
"equationName": "displacement",
"equationTeX": "x_{f}=x_{0}+v_{0}t+\\frac{1}{2}at^{2}",
"equationVariables": [{
"variableTeX": "x_{f}",
"variableDescription": "The final displacement"
},
{
"variableTeX": "x_{0}",
"variableDescription": "The initial displacement (starting point)"
},
{
"variableTeX": "v_{0}",
"variableDescription": "The initial velocity"
},
{
"variableTeX": "t",
"variableDescription": "The time elapsed"
},
{
"variableTeX": "a",
"variableDescription": "acceleration"
}
]
}
]
}
这是我到目前为止拥有的HTML:
<!DOCTYPE html PUBLIC "testPage">
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Testing javscript stuff</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-MML-AM_CHTML' async></script> <!-- call for TeX reader -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!-- Call for JSON getter -->
</head>
<body>
\[v_{f}^{2}=v_{i}^{2}+2a(x-x_{0})\]
<script src="SECAPS.js"></script>
</body>
</html>
SECAPS.js文件在这里
var equations ={};
$.getJSON('equations.json', function(data) {
equations=data;
});
document.write("The equation group name is:" + equations.equationGroup[0].equationGroupName);
答案 0 :(得分:0)
您的JSON格式错误。在最后一行添加“]}。 在enter link description here
检查您的JSON$。getJSON是异步的。因此需要异步false。
$.ajaxSetup({
async: false
});
var equations = {};
$.getJSON('test1.json', function(data) {
equations = data;
console.log(data.equationGroup);
console.log(equations);
console.log(equations.equationGroup);
});
console.log(equations);
document.write("The equation group name is:" + equations.equationGroup[0].equationGroupName);
答案 1 :(得分:-1)
我认为您正在寻找这个:
var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
或
var obj = JSON.parse('path/to/json/file.json');
此后,您可以访问数据。
示例:alert(obj.name)