【发布时间】:2014-08-15 09:23:46
【问题描述】:
所以我在 StackExchange 和其他网络论坛上查看并查看了不同的答案,但我仍然不明白这一点。 我有一个 .json 文件,其中包含来自 excel 文档的信息。 我想在网络浏览器上显示它 -> 最简单的方法似乎是用 html 编写它。
如何用 html 打开 JSON 文件?我很高兴将整个 JSON 文件显示在 html 脚本上,但我希望能够将 is 设置为变量并像普通 JSON 对象一样从中提取内容。
我有下面的代码来制作我想要做的表格 - 但真正的 JSON 对象在一个单独的文件中。
<html>
<head>
<title>Creation of array object in javascript using JSON</title>
<script language="javascript" >
document.writeln("<h2>JSON array object</h2>");
var books = { "Pascal" : [
{ "Name" : "Pascal Made Simple", "price" : 700 },
{ "Name" : "Guide to Pascal", "price" : 400 }
],
"Scala" : [
{ "Name" : "Scala for the Impatient", "price" : 1000 },
{ "Name" : "Scala in Depth", "price" : 1300 }
]
}
var i = 0
document.writeln("<table border='2'><tr>");
for(i=0;i<books.Pascal.length;i++)
{
document.writeln("<td>");
document.writeln("<table border='1' width=100 >");
document.writeln("<tr><td><b>Name</b></td><td width=50>"
+ books.Pascal[i].Name+"</td></tr>");
document.writeln("<tr><td><b>Price</b></td><td width=50>"
+ books.Pascal[i].price +"</td></tr>");
document.writeln("</table>");
document.writeln("</td>");
}
for(i=0;i<books.Scala.length;i++)
{
document.writeln("<td>");
document.writeln("<table border='1' width=100 >");
document.writeln("<tr><td><b>Name</b></td><td width=50>"
+ books.Scala[i].Name+"</td></tr>");
document.writeln("<tr><td><b>Price</b></td><td width=50>"
+ books.Scala[i].price+"</td></tr>");
document.writeln("</table>");
document.writeln("</td>");
}
document.writeln("</tr></table>");
</script>
</head>
<body>
</body>
</html>
澄清一下:上面的代码很好用;但我想使用保存在本地驱动器上的 .json 文件的内容来完成。
提前致谢。
【问题讨论】:
-
要在初始 HTML 页面之外加载 JSON,您需要使用后台请求(通常称为 AJAX)来执行此操作。加载 JSON 数据的最简单方法是使用带有可靠文档、示例等的 Javascript 库,以及执行所需操作的简单界面。 Jquery can help you there
-
感谢所有回复的人!我将尝试所有这些答案,看看哪个最适合我的项目。后续问题:很多人提到jquery(@Brian)这被广泛认为是“正确”的做法吗?我应该继续下载吗?
-
jQuery 不是“正确”的做法,但是与调用 jQuery 的
getJSON方法相比,进行自己的 AJAX 调用是一个非常复杂的过程。您的代码向我表明您对 Javascript 开发相对较新(我们都曾经是没有错的:P),因此,像 jQuery 这样的库可能是一个很好的跳板让您继续前进:) -
谢谢布赖恩,我会调查的。
标签: javascript html json browser