I'm trying to get the JSON contents of a file via JSON, but I can't get it to work. My file tree looks like this:
- root
- js
- script.js
- json
- data.json
- js
I can't reach the data.json
file from my Javascript script. Here's my code:
var data, request;
if (window.XMLHttpRequest){
request = new XMLHttpRequest();
} else {
request = new ActiveXObject('Microsoft.XMLHTTP');
}
request.open('GET', '../json/data.json'); // This works fine when the script is placed in the root and the ../ is removed, but when I move it into the js folder it breaks.
request.onreadystatechange = function() {
if ((request.readyState == 4) && (request.status==200)) {
var data = JSON.parse(request.responseText);
if (data) {
return data;
} else {
return "No data found";
}
}
}
request.send();
console.log(data);
The expected result is it returns an object from the JSON folder or print "No data found". Instead I just get undefined
in my console. This means my only problem is actually finding that file. I don't normally use JavaScript so I'm probably just not using the right syntax, but since ../json/data.json
clearly is incorrect, what is?