如何在没有Web请求或Web服务器的情况下解析JSON文件? [英] How to parse a JSON file without web request or web server?
问题描述
希望建立以下解决方法.
Looking to build a work-around of the following.
$.getJSON('myfile.json', function (data) {
showAll(data);
});
我想避免使用网络服务器,而只想直接访问文件.
I want to avoid using a webserver, but just want to access the file directly.
getJSON
使用一个Web请求,该请求显示错误:XMLHttpRequest cannot load file:///Users/me/Documents/project/myfile.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
getJSON
uses a web request, which presents the error: XMLHttpRequest cannot load file:///Users/me/Documents/project/myfile.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
我要解决.我已经阅读了有关重命名为.js
的内容,然后仅将其从HTML文件进行链接.有什么想法吗?
I want a work around. I've read things about renaming to .js
and then just linking it from the HTML file. Any ideas?
推荐答案
简单,快速,但对实际项目解决方案不利:
Simple, fast, but bad for real project solution:
- 将
myfile.json
重命名为data.js
(名称无关紧要). - 在data.js中创建一个变量,并使用json对其进行初始化
var myData = {...your json...}
- 将
<script src="./data.js"></script>
添加到您的html文件中. - 现在,您可以将javascript中的
myData
变量用于所有数据.
- Rename
myfile.json
todata.js
(name doesn't matter). - Create a variable in data.js and initialize it with your json
var myData = {...your json...}
- Add
<script src="./data.js"></script>
to your html file. - Now you can use
myData
variable from javascript with all data.
此解决方案不好,因为您在全局范围内添加了一个新变量,并且浏览器仍会发出http请求来获取此.js文件.
This solution is bad because you add a new variable in global scope and browser would still make a http request to get this .js file.
此外,如果要向本地文件发出Ajax请求,则可以使用http服务器.看看非常简单的节点js http服务器.
Also, If you want to make ajax requests to your local files, you can use http server. Take a look at very simple node js http-server.
这篇关于如何在没有Web请求或Web服务器的情况下解析JSON文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!