CLIX159 CLIX159 - 7 months ago 235
HTML Question

Load a JSON file in local system using jQuery/Javascript

I am new to scripting languages. I have a

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

When my HTML file loads the
new.json
file using
$.getJSON
, 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() {
//read(a)
var myItems;

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


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
new.json
and
gary.html
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
gary.html
and it loads the data of
new.json
file.

How can I achieve that?

Answer

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:

<head>
    <script src="jquery.js"></script>
    <script src="new.json"></script>
    <script>
        $(function() {
            newJson.a.forEach(function(item) {
                console.log(item.name);
            });
        })
    </script>
</head>