Javascript JQuery.getJSON() 读取本地文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11297219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:21:39  来源:igfitidea点击:

JQuery.getJSON() reading a local file

javascriptjqueryjsonlocal-files

提问by user1167650

How do you read a file in the current directory using JQuery.getJSON()?

如何使用 JQuery.getJSON() 读取当前目录中的文件?

I'm trying something simple (with my data.json file in the same directory as my html file):

我正在尝试一些简单的事情(我的 data.json 文件与我的 html 文件在同一目录中):

$.getJSON("./data.json")

and I get the error:

我得到错误:

XMLHttpRequest cannot load file:///C:/Projects/test/data.json. Origin null is not allowed by Access-Control-Allow-Origin.

XMLHttpRequest 无法加载 file:///C:/Projects/test/data.json。Access-Control-Allow-Origin 不允许 Origin null。

I've tried all sorts of combinations of path, but it doesn't seem to work...

我尝试了各种路径组合,但似乎不起作用......

EDIT: I'm using Chrome, but I'd like to work in all browsers...

编辑:我正在使用 Chrome,但我想在所有浏览器中工作...

回答by ephemient

If you are using Google Chrome, it is intentional that AJAX on file:///paths never works.

如果您使用的是 Google Chrome,那么file:///路径上的 AJAX永远不会起作用是有意为之。

crbug/40787

crbug/40787

回答by Utkanos

This is because you're running your web files directly from your hard drive. There are various pitfalls in this, one of which you have found. Ideally you want to be working in a server environment, even locally. You can install a (free) local LAMP server such as XAMPP. Then, you'll be able to use local AJAX.

这是因为您直接从硬盘驱动器运行 Web 文件。这其中存在各种陷阱,您已经发现了其中之一。理想情况下,您希望在服务器环境中工作,甚至在本地工作。您可以安装(免费)本地 LAMP 服务器,例如XAMPP。然后,您将能够使用本地 AJAX。

回答by William Daly

An alternative to installing a local LAMP server is to use python's simple HTTP server. As long as you have python installed, just open up bash and use the python interpreter.

安装本地 LAMP 服务器的替代方法是使用 python 的简单 HTTP 服务器。只要你安装了python,打开bash并使用python解释器即可。

For python 2 use:

对于 python 2 使用:

python -m SimpleHTTPServer 8000

For python 3 use:

对于 python 3 使用:

python -m http.server 8000

Then just point your browser at localhost:8000 and you shouldn't have any trouble accessing the file if it's in the same directory.

然后只需将浏览器指向 localhost:8000 ,如果它在同一目录中,则访问该文件应该不会有任何问题。

回答by xvatar

It's not about path

这不是关于路径

It's a cross-domain problem

这是跨域问题

Basically you need to add a callback in your URL, so that jQuery can automatically change the request type from json to jsonp

基本上你需要在你的 URL 中添加一个回调,以便 jQuery 可以自动将请求类型从 json 更改为 jsonp

See this postfor detail

看到这个帖子查看详细