在纯JavaScript中加载多个JSON文件 [英] Load multiple JSON files in pure JavaScript

查看:841
本文介绍了在纯JavaScript中加载多个JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是javaScript的新手。我已经了解了如何使用JSON.Parse()从JSON文件创建对象,现在我需要将多个本地JSON加载到数组中。我一直在谷歌搜索我的问题,但我发现的所有内容都与单个文件有关。
有没有办法在没有jQuery等库的纯JS中做到这一点?

I am new to javaScript. I have already understood how to create object from JSON-file with JSON.Parse() and now I need to load multiple local JSONs into array. I've been googling my problem for a while, but everything that I found was related to single file. Is there any way to do this in pure JS without any libraries like jQuery and etc.?

PS:没有必要使用web-server或者,代码在本地运行。

P.S.: There is no need to work with web-server or else, the code is running locally.

推荐答案

为此,您需要先获取实际文件。然后,你应该解析它们。

To do this, you need to first get the actual files. Then, you should parse them.

// we need a function to load files
// done is a "callback" function
// so you call it once you're finished and pass whatever you want
// in this case, we're passing the `responseText` of the XML request
var loadFile = function (filePath, done) {
    var xhr = new XMLHTTPRequest();
    xhr.onload = function () { return done(this.responseText) }
    xhr.open("GET", filePath, true);
    xhr.send();
}
// paths to all of your files
var myFiles = [ "file1", "file2", "file3" ];
// where you want to store the data
var jsonData = [];
// loop through each file
myFiles.forEach(function (file, i) {
    // and call loadFile
    // note how a function is passed as the second parameter
    // that's the callback function
    loadFile(file, function (responseText) {
        // we set jsonData[i] to the parse data since the requests
        // will not necessarily come in order
        // so we can't use JSONdata.push(JSON.parse(responseText));
        // if the order doesn't matter, you can use push
        jsonData[i] = JSON.parse(responseText);
        // or you could choose not to store it in an array.
        // whatever you decide to do with it, it is available as
        // responseText within this scope (unparsed!)
    }
})

如果你不能发表XML请求,你也可以使用文件阅读器对象:

If you can't make an XML Request, you can also use a file reader object:

var loadLocalFile = function (filePath, done) {
    var fr = new FileReader();
    fr.onload = function () { return done(this.result); }
    fr.readAsText(filePath);
}

这篇关于在纯JavaScript中加载多个JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆