JQuery.getJSON() reading a local file

无人久伴 提交于 2019-12-17 20:50:00

问题


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

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

$.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.

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...


回答1:


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

crbug/40787




回答2:


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.




回答3:


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.

For python 2 use:

python -m SimpleHTTPServer 8000

For python 3 use:

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.




回答4:


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

See this post for detail



来源:https://stackoverflow.com/questions/11297219/jquery-getjson-reading-a-local-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!