Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
878 views
in Technique[技术] by (71.8m points)

javascript - $.getJSON not working with local JSON file

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...