在纯JavaScript中加载多个JSON文件
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了在纯JavaScript中加载多个JSON文件,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1641字,纯文字阅读大概需要3分钟。
内容图文
![在纯JavaScript中加载多个JSON文件](/upload/InfoBanner/zyjiaocheng/705/d558005f53254444b863b26291784d63.jpg)
我是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);
}
内容总结
以上是互联网集市为您收集整理的在纯JavaScript中加载多个JSON文件全部内容,希望文章能够帮你解决在纯JavaScript中加载多个JSON文件所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。