问题
I am new to the use of JSON.
I want my webpage to display, in a table, a small database of a few hundred records. Wanting to avoid the hassle of putting my data in a MySQL database or something similar, I figured I would read my data from a JSON file, and write it out to a JSON file, and that this would amount to convenient, persistent storage of my database at my website.
So I spent a bit of time writing a script that translated my existing papers file into a papers.json file that contains all my records. It looks like:
[
{"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"
}
]
Here is the javascript code I am using to read it. (I haven't yet coded the write-out of the records, because the read isn't working.)
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();
});
The script hangs in the while loop forever. Why?
Also I am new to jQuery. I would feel more comfortable doing this without the use of a library, one new thing at a time being enough for me. Can one manipulate JSON files easily without jQuery?
回答1:
Normal browser JavaScript is single-threaded. Precisely because the infinite while
never ends, the JavaScript engine never gets to process the success callback of the $.getJSON
call. Your browser's sole JS thread sits looping forever and never moves on to the callback.
Solution: You should eliminate the loop and move code that is currently after the infinite loop into your $.getJSON
callback.
来源:https://stackoverflow.com/questions/10759638/using-a-json-file-to-store-a-small-database-persistently-in-javascript