$.getJSON not working with local JSON file

前端 未结 8 1091
野趣味
野趣味 2021-01-15 08:56

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.

相关标签:
8条回答
  • 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

    0 讨论(0)
  • 2021-01-15 09:22

    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?

    0 讨论(0)
  • 2021-01-15 09:23

    XmlHttpRequest isn't allowed cross-domain.

    If you need to do a demonstration on a local pc, setup your web app to run on local webserver, and have the json source be returned be the same web application.

    That's the only way I can think to make it work. You can't use Ajax calls on filesystem for security reasons.

    0 讨论(0)
  • 2021-01-15 09:23

    try https://jsonbin.io/ with making the bin as public and provide the url to the getJSON cal

    $.getJSON("https://api.jsonbin.io/b/58f9f835a3de5638", function(data) {}
    
    0 讨论(0)
  • 2021-01-15 09:26

    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.

    0 讨论(0)
  • 2021-01-15 09:27

    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+'"/>
            });
          }
    );
    
    0 讨论(0)
提交回复
热议问题