$.getJSON not working with local JSON file

2020-03-30 01:14发布

I am desperately trying to get a local build of a site to get a JSON file (also local) with no luck. The exact code worked perfect on my server, but once local, breaks.

I get the JSON with jQuery like so:

$.getJSON(
 "lib/js/app.json",
     function(data){
        $.each(data, function(i,user){
        +'<img src="'+user.thumbnail+'"/>
        });
      }
);

And receive this console error:

XMLHttpRequest cannot load file://localhost/Users/blakestruhs/new/lib/js/app.json. Origin null is not allowed by Access-Control-Allow-Origin.

I'm dying for an answer here. Please help me.

7条回答
叼着烟拽天下
2楼-- · 2020-03-30 01:51

You should use http://localhost over file://localhost;

$.getJSON(
 "http://localhost/Users/blakestruhs/new/lib/js/app.json",
     function(data){
        $.each(data, function(i,user){
        +'<img src="'+user.thumbnail+'"/>
        });
      }
);
查看更多
乱世女痞
3楼-- · 2020-03-30 01:57

Instead of using getJSON, for browsers which support it (including Chrome) you can use the FileReader API.

var r = new FileReader();
r.onload = function(e) {
        var obj = JSON.parse(e.target.result);
        // do what you will with the object
}
// Start the async read
r.readAsText(file);

Note that the file variable needs to be a File or Blob object. The easiest way to get one is to let the user choose it from a file input element. If you need to read a file without asking the user, you might check out: https://stackoverflow.com/a/30896068/2476389

查看更多
The star\"
4楼-- · 2020-03-30 01:59

JSON has to load over the HTTP protocol rather than the local file protocol.

The cross domain complaint is that it'll treat each file as a different domain so you need to run it in a web server.

either set up a local webserver or store your JSON in a variable instead and skip getJSON altogether.

查看更多
爷的心禁止访问
5楼-- · 2020-03-30 02:02

Chrome doesn't allow ajax calls to be made to local files. Refer This

查看更多
对你真心纯属浪费
6楼-- · 2020-03-30 02:09

I think you use a Webkit browser like chrome, right? Chome does'n see a relation between two local files. Use Firefox or run it on a webserver ;)

"Origin null is not allowed by Access-Control-Allow-Origin" in Chrome. Why?

查看更多
小情绪 Triste *
7楼-- · 2020-03-30 02:10

I think if you access the page that calls the getJSON with the IP address then use the ip address instead of localhost for the json file, effectively they belong to the same domain and it should work

查看更多
登录 后发表回答