Vanilla JS:如何检索json文件,将结果解析成数组,并访问每个对象

问题描述

假设我有一个名为 map.json 的 json 文件

{
    "images":{
        "background": ["images/mountains.png","images/sea.png"]
    }
}

我想要的是让 javascript 访问 map.json 中的“images/mountains.png”,然后使用它来检索 Mountains.png 文件。我在网上找到了这个简洁的代码,我在整个代码之上使用了它:

var xh_req = new XMLHttpRequest();
xh_req.open("GET","map.json",false);
xh_req.send(null);
var json_object = JSON.parse(xh_req.responseText);

这基本上是允许javascript通过简单地输入json_object.images.background[n]来访问map.json中的对象。所以,如果我想从 map.json 获取“images/sea.png”,我只需输入 json_object.images.background[1] 就可以了。如果不是因为控制台不断向我抛出警告,这将是结束。它说:

[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.

在接下来的几个小时里,我一直试图通过阅读论坛和 XMLHttpRequest 文档来解决这个问题,并使用我发现的任何知识来重写与上述功能相同的代码。然而,我似乎做不到。我可能错过了一些重要的点,这就是为什么我仍然无法编写正确的代码。有人能帮我解决这个问题吗?

解决方法

该代码的问题在于它使用 false 作为 async 参数。

最小的变化就是这样做:

var xh_req = new XMLHttpRequest();
xh_req.open("GET","map.json"); // No `false`
xh_req.send(null);
xh_req.onload = () => {
    const data = JSON.parse(xh_req.responseText);
    // ...your code using `data` (it's not JSON,so I renamed it) here...
};
xh_req.onerror = error => {
    // ...show/handle error...
};

但是,我建议改用fetch

fetch("map.json")
.then(response => {
    if (!response.ok) {
        throw new Error(`HTTP error ${response.status}`);
    }
    return response.json();
})
.then(data => {
    // ...your code using `data` here...
})
.catch(error => {
    // ...show/handle error...
});

请注意,在这两种情况下,任何想要使用文件中数据的代码都不能在调用完成之前运行,这就是为什么我在上面使用 {{1} }

如果您使用现代浏览器并将代码作为模块加载,则可以使用顶级 data,如果您可以不自己处理错误而是让浏览器只需将其转储到控制台:

await

再说一次,这不是处理错误。