我对JSON的使用是个新手。
我希望我的网页在一个表格中显示一个包含几百条记录的小型数据库。为了避免将数据放入MySQL数据库或类似数据库的麻烦,我想我可以从JSON文件中读取数据,并将其写到JSON文件中,这将相当于在我的网站上方便、持久地存储我的数据库。
因此,我花了一些时间编写了一个脚本,将现有的论文文件转换为包含所有记录的papers.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文件吗?
发布于 2012-05-26 02:32:36
普通的浏览器JavaScript是单线程的。正是因为无限的while永远不会结束,所以JavaScript引擎永远不会处理$.getJSON调用的成功回调。浏览器的惟一JS线程永远处于循环状态,并且永远不会移动到回调。
解决方案:您应该消除循环,并将当前在无限循环之后的代码移动到$.getJSON回调中。
https://stackoverflow.com/questions/10759638
复制相似问题