【发布时间】:2012-05-29 13:40:24
【问题描述】:
我不熟悉 JSON 的使用。
我希望我的网页在表格中显示一个包含数百条记录的小型数据库。为了避免将数据放入 MySQL 数据库或类似数据库的麻烦,我想我会从 JSON 文件中读取数据,并将其写入 JSON 文件,这相当于方便、持久地存储我的我网站上的数据库。
所以我花了一些时间编写一个脚本,将我现有的论文文件翻译成一个包含我所有记录的 paper.json 文件。它看起来像:
[
{"title" : "IEEE Standard for Local and Metropolitan Area Networks: Overview and Architecture",
"authors" : "IEEE",
"pub" : "IEEE 802-2001 standard",
"datepub" : "2001",
"keywords" : "MAC",
"dateread" : "200309",
"physloc" : "box i",
"comment" : "Indicates how you can manage addresses assigned to you by IEEE."
},
{"title" : "A framework for delivering multicast messages in networks with mobile hosts",
"authors" : "A. Acharya, B. R. Badrinath",
"pub" : "Mobile Networks and Applications v1 pp 199-219",
"datepub" : "1996",
"keywords" : "multicast mobile MH MSS",
"dateread" : "",
"physloc" : "box a",
"comment" : ""
},
<hundreds more similar papers records here...>
},
{"title" : "PiOS: detecting privacy leaks in iOS applications",
"authors" : "M. Egele, C. Kruegel, E. Kirda, G. Vigna",
"pub" : "NDSS 2011",
"datepub" : "2011",
"keywords" : "iOS app location leakage",
"dateread" : "",
"physloc" : "box e",
"comment" : "discussed at Latte"
}
]
这是我用来阅读它的 javascript 代码。 (我还没有对记录的写出进行编码,因为读取不起作用。)
var pdb = []; // global
var doneReading = false; //global
$(document).ready(function() {
$.getJSON('papers.json',function(data) {
pdb = data;
doneReading = true;
});
while (!doneReading) {}
alert("finished assignment of JSON to pdb"+" "+typeof pdb);
//alert(pdb[0].title);
console.log(pdb[2]);
//setup();
});
脚本永远挂在while循环中。为什么?
我也是 jQuery 的新手。如果不使用图书馆,我会感觉更舒服,一次一件新事物对我来说就足够了。不使用 jQuery 可以轻松操作 JSON 文件吗?
【问题讨论】:
-
呃为什么不把警报/日志放在
getJSON回调中? -
好的,谢谢。通过将我的代码更改为此,它起作用了: $(document).ready(function() { $.getJSON('papersdb.52.json', pdb, function(data) { pdb = data; alert(pdb[1] .title); }); });
-
没有jQuery.getJSON的情况下有没有简单的方法使用JSON?
-
我曾经对 RESTful Web api 服务进行 ajax 调用,我从未尝试过做本地存储,所以......我不知道。我确实知道,如果您查看 Backbone.Js,他们有一个本地存储插件,可以使模型持久化到本地无缝。
标签: javascript json persistent-storage