我如何使用jQuery从JSON文件中读取特定内容?

时间:2016-07-13 16:47:27

标签: javascript jquery json

我正在尝试制作自己的基于平铺的游戏;一个非常简单的。我决定将必要的级别数据放入JSON文件中,以便通过我对游戏引擎的原始尝试来读取。

{
    "tileset":"main.png",
    "layers":[
        [
            [8 ,8 ,8 ,8 ,8 ,8 ,8 ,8 ,8 ,8 ,8 ],
            [0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ],
            [0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ],
            [0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ],
            [0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ],
            [0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ],
            [0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ],
            [3 ,3 ,3 ,3 ,2 ,0 ,0 ,0 ,0 ,0 ,0 ],
            [1 ,1 ,1 ,1 ,5 ,0 ,0 ,0 ,0 ,0 ,0 ]
        ], [
            [1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ],
            [0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ],
            [0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ],
            [0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ],
            [0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ],
            [0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ],
            [0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ],
            [1 ,1 ,1 ,1 ,1 ,0 ,0 ,0 ,0 ,0 ,0 ],
            [1 ,1 ,1 ,1 ,1 ,0 ,0 ,0 ,0 ,0 ,0 ]
        ]
    ]
}

然而,我是JavaScript之类的完全新手,甚至jQuery也有点让我头疼。我如何读取此文件,然后将每个图层的锯齿状数组放入自己的变量中?

e.g。取第一层阵列并将其放入,例如var first_layer,依此类推等等

1 个答案:

答案 0 :(得分:1)

请参阅this小提琴。

您可以使用$.get() function作为jQuery ajax函数的包装器。你如何处理数据取决于你,我只是出于演示目的而进行处理。

$.get("/echo/json/", function(data) {
  var data = json; // only for fiddle
  data.layers.forEach(function(layer, index) {
    $("body").append("<ul class=\"list-unstyled layer\" data-index=\"" + index + "\"></ul>");
    layer.forEach(function(row) {
      $(".layer[data-index=" + index + "]").append("<li>" + JSON.stringify(row) + "</li>");
    });
  });
}, "json");

您需要对JSON数据进行微调(这些图层需要封装在一个数组中,否则它是无效的JSON - check online)。

您可以更改框中JSON文件的URL的/echo/json/。那么数据分配是不必要的(我需要它,因为我不能在小提琴中使用AJAX)。

如果您需要我扩展所使用的任何技术,请询问。