简体   繁体   English

使用Javascript / jQuery读取JSON

[英]Reading JSON with Javascript/jQuery

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. 我正在javascript / html5中构建游戏,我正在尝试在迷宫中构建一个锁定门的数据库,可以在整个游戏过程中加载和覆盖。 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: 我的JSON文件如下所示:

{
"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: 我想构建HTML页面,以便当玩家与门碰撞时,它会检查它是否锁定:

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. 但是我在阅读JSON文件本身时遇到了麻烦。 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. 但没有任何反应,我也需要能够访问HTML中的信息。 I'd rather use jQuery, but I'm not opposed to straight JS if it works. 我宁愿使用jQuery,但如果它有效,我不反对直接JS。 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! 谢谢!

Perhaps you should use the traditional function jQuery.ajax and have the response parsed as json. 也许你应该使用传统的函数jQuery.ajax并将响应解析为json。 I always found it to be easier to debug. 我总是发现它更容易调试。

jQuery.ajax({
    url:'info.json',
    dataType:'json'
}).done(function(response) {
   console.log(response.doors);
});

please note that the first element of the response is not response[0] but response.doors. 请注意,响应的第一个元素不是响应[0]而是响应。

Besides... I don't get the data structure. 除此之外......我没有得到数据结构。 How come you have a "left" key in several positions? 你怎么在几个位置上有一个“左”键?

$.get('info.json',{},function(data){

    console.log(data.doors);
});

that is it . 这就对了 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM