Reading JSON with Javascript/jQuery
Posted
by
Josephine
on Stack Overflow
See other posts from Stack Overflow
or by Josephine
Published on 2013-11-03T21:05:38Z
Indexed on
2013/11/03
21:55 UTC
Read the original article
Hit count: 234
I'm building a game in javascript/html5 and I'm trying to build a database of locked doors in a maze that can be loaded from and overwritten to throughout gameplay. I've found a large number of tutorials online, but nothing is working. I was wondering if someone could look at what I'm trying and let me know what I'm doing wrong.
My JSON file looks like this:
{
"doors": [
{"left":true, "right":false, "bottom":false},
{"left":false, "right":false, "bottom":false},
{"right":false, "bottom":false, "top":false},
{"left":false, "right":false, "top":false}
]
}
I want to build the HTML page so that when a player collides with a door it checks if its locked or not like:
if (player.x < leftDoor.x + leftDoor.width &&
player.x + player.width > leftDoor.x &&
player.y < leftDoor.y + leftDoor.height &&
player.y + player.height > leftDoor.y)
{
if(doors[0].left == true)
alert("door is locked");
else
window.location = ( "2.html?p1=");
}
However I'm having trouble reading from the JSON file itself. I've tried things like:
function loadJson() {
$(document).ready(function()
{
$.getJSON('info.json', function(doors) {
alert(doors[0].left);
});
});
}
But nothing happens, and I need to be able to access the information in the HTML as well. I'd rather use jQuery, but I'm not opposed to straight JS if it works. I've been trying to do this for ages and I'm getting absolutely no where. If someone could help that would be amazing. Thanks!
© Stack Overflow or respective owner