简体   繁体   English

如何使用JavaScript读取本地json文件?

[英]How to read a local json file using javascript?

I want to load data from a JSON file in my local using JS/jQuery preferably. 我想最好使用JS / jQuery从本地JSON文件中加载数据。

I know there are atleast 10 question on SO with the same answers. 我知道至少有10个关于SO的问题具有相同的答案。

I don't want those. 我不要那些 In all of those answers I get a " jquery.min.js:4 XMLHttpRequest cannot load file:///C:/Users/.../js.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource. " 在所有这些答案中,我得到一个“ jquery.min.js:4 XMLHttpRequest cannot load file:///C:/Users/.../js.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

Please suggest me a solution to this. 请为我提出解决方案。 If your suggestion is set up a server and host the file there then use it, please help me do it? 如果您的建议是设置服务器并在此处托管文件,然后使用它,请帮助我吗?

Any possible working suggestion is welcome(except the old add json using a script tag, etc). 欢迎任何可能的工作建议(使用脚本标记的旧add json等除外)。 Thanks. 谢谢。

You are making an http request to the local file system, that is not possible. 您正在向本地文件系统发出http请求,这是不可能的。

Check that limited support in HTML5 with the file API but I still doubt its what you want. 使用文件API来检查对HTML5的有限支持,但我仍然怀疑您想要什么。

http://www.html5rocks.com/en/tutorials/file/dndfiles/ http://www.html5rocks.com/zh-CN/tutorials/file/dndfiles/

使用JSON服务器https://github.com/typicode/json-server来运行本地JSON服务器,而不是直接访问磁盘。

You should use a local webserver such as XAMPP/LAMP/MAMP or IIS/Apache. 您应该使用本地Web服务器,例如XAMPP / LAMP / MAMP或IIS / Apache。 A related question that should help is here . 这里应该提供一个相关的问题。 Another solutions that might work if you really want just filesystem are using iframe and HTML5 FileSystem APIs. 如果您真的只想要文件系统,则另一种可能有效的解决方案是使用iframe和HTML5 FileSystem API。

EDIT: When setting XAMPP, after putting your files into htdocs, you might have to set header Access-Control-Allow-Origin * . 编辑:设置XAMPP时,将文件放入htdocs后,您可能必须设置标头Access-Control-Allow-Origin * This can be achieved with putting this into .htaccess file in the htdocs directory: 可以通过将其放入htdocs目录中的.htaccess文件中来实现:

Header set Access-Control-Allow-Origin "*"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM