Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
11
rated 0 times [  17] [ 6]  / answers: 1 / hits: 38126  / 12 Years ago, thu, july 19, 2012, 12:00:00

How do I load an object into javascript if it is available in a json file?



I have the following script in my html:



<script src='scene.json'></script>
<script>
var x = scene.x;
</script>


And this is the file scene.json, located in the same folder:



{scene: {
x: 0,
y: 0,
w: 11000,
h: 3500,
}}


But the json file is not loaded properly (unexpected token ':') and the scene.x reference is also probably not the way it should be done. Is it possible to refer to the data directly? Or does it need to be loaded by some http request?


More From » json

 Answers
36
{scene: {
x: 0,
y: 0,
w: 11000,
h: 3500
}}


Is invalid javascript (because it's treated as a block), you probably just want a javascript file:



var scene = {
x: 0,
y: 0,
w: 11000,
h: 3500
};


If you want to keep the file as JSON, you cannot reference it from a script element and have it work while being valid JSON. You would need to use ajax request to fetch the file and parse the JSON.


[#84149] Wednesday, July 18, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aubriea

Total Points: 641
Total Questions: 118
Total Answers: 101

Location: French Southern and Antarctic Lands
Member since Fri, Jan 6, 2023
1 Year ago
;