ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

在纯JavaScript中加载多个JSON文件

2019-10-01 09:44:03  阅读:224  来源: 互联网

标签:local-files javascript json


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

P.S.:没有必要使用Web服务器,否则代码在本地运行.

解决方法:

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

// 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请求,还可以使用文件读取器对象:

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

标签:local-files,javascript,json
来源: https://codeday.me/bug/20191001/1838468.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有