$.getJSON not working with local JSON file

前端 未结 8 1171
野趣味
野趣味 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条回答
  •  不要未来只要你来
    2021-01-15 09:21

    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

提交回复
热议问题