I'm stuck trying to get the correct path to the local file. I have the following directories:
Resources ->
data ->
file.json
js ->
folder ->
script.js
html ->
folder ->
file1.html
I'm executing script.js
from file1.html
, with js code:
var answers = JSON.parse('../../data/file.json');
alert(answers);
But it doesn't work, even alert is not starting. What is wrong?
Also I've tried this:
function readJSON(file) {
var request = new XMLHttpRequest();
request.open('GET', file, false);
request.send(null);
if (request.status == 200)
return request.responseText;
};
var temp = readJSON('../../data/file.json');
alert(temp);
Alert undefined in this case.
If
Resources
is the root path, best way to accessfile.json
would be via/data/file.json
This solution uses an Asynchronous call. It will likely work better than a synchronous solution.
Since it is in the directory
data/
, You need to do:file path is
'../../data/file.json'
Pure JS:
Loading local JSON file
Use something like this
My case of working code is:
This code worked for me.