I try to load a json file from my local project which is not running on a webserver.
test.json
[{
name : "Google",
url : "https://www.google.com",
},
{
name : "Bing",
url : "https://www.bing.com",
}]
First attempt:
First I tried it by using the local file which is inside the project folder.
loadJSON("data/test.json", function(response) {
console.log(JSON.parse(response));
});
function loadJSON(path, callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', path, true); // Replace 'my_data' with the path to your file
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
Response:
index.html:616 Failed to load file:///C:/wamp64/www/projects/Startseite/data/test.json: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
Then I researched the error, set up a virtual host and changed the call to this:
loadJSON("http://ressources/data/test.json", function(response) {
console.log(JSON.parse(response));
});
Response:
Failed to load http://ressources/data/test.json: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Is it even possible to load json without using a webserver or installing browser plugins which changes the header?