CLIX159 CLIX159 - 2 months ago 41x
HTML Question

Load a JSON file in local system using jQuery/Javascript

I am new to scripting languages. I have a

file and I want to load in
HTML file. I do not want to run
file on server. I want to run it locally on my machine.

When my HTML file loads the
file using
, I get a blank screen and when I checked on console I get the error:

jquery-3.1.0.js:9392 XMLHttpRequest cannot load file:///C:/Users/Gary/Desktop/new.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.`

and this my loading code

function show() {
var myItems;

$.getJSON('new.json', function(data) {
myItems = data.a;

When I googled for this error, people suggest to me run this file on firefox, or execute this
chrome --allow-file-access-from-files
. The file is loading in firefox and when I am executing the
chrome --allow-file-access-from-files
, the File also loads in chrome.

My main concern is that when I distribute the
file to others then others may or may not have firefox or chrome's
chrome --allow-file-access-from-files
permission. I just want user to click on
and it loads the data of

How can I achieve that?


As you've seen - you can't make AJAX requests to the local filesystem as it's a huge security issue. The only workaround for this is for the user to manually enable settings in their browser (which is not a great idea anyway). If you do not want this then you will have to use a central server for all requests.

The alternative is to avoid using AJAX by including the new.json file in the page using an extra <script /> tag. You will also need to assign the object to a variable in the file, something like this:

// new.json
var newJson = {"a": [{"name":"avc"}, {"name":"Anna"}, {"name":"Peter"}]}

Then in gary.html:

    <script src="jquery.js"></script>
    <script src="new.json"></script>
        $(function() {
            newJson.a.forEach(function(item) {