Originally my Json data was in a php file together with code to parse it. They look like:
main.php
<script>
var pdatabase= '{ "pobject" : [' +
'{ "pname":"Pikachu" , "pid":"1" },' +
'{ "pname":"Squirtle" , "pid":"2" },' +
'{ "pname":"Justinbieber" , "pid":"3" }]}';
</script>
<script>
$(function() {
ppdatabase = JSON.parse(pdatabase);
plenth=ppdatabase.pobject.length;
test=console.log(plenth);
});
</script>
Then I found this is terrible to manage my Json data. So I migrate the Json data to a separate file named "obdatabase.json".
obdatabase.json
var pdatabase= '{ "pobject" : [' +
'{ "pname":"Pikachu" , "pid":"1" },' +
'{ "pname":"squirtle" , "pid":"2" },' +
'{ "pname":"Justinbieber" , "pid":"3" }]}';
In the main.php, after deleting original json data, I made two attempts to access the data and parse it,but failed.
First try
<script src="obdatabase.json"></script>
<script>
$(function() {
ppdatabase = JSON.parse(pdatabase);
plenth=ppdatabase.pobject.length;
test=console.log(plenth);
});
</script>
Second Try
<script>
$.get('obdatabase.json', function(pdatabase) {
ppdatabase = JSON.parse(pdatabase);
plenth=ppdatabase.pobject.length;
test=console.log(plenth);
});
</script>
So how to fix this?