Currently, I am attempting to use vanilla JS AJAX request in order to retrieve a JSON string from a locally stored JSON file. My main objective is to accomplish this without relying on JQuery. The code snippet below was inspired by this answer. Despite my efforts, I keep encountering an error in the Chrome console (refer to the message provided). Could someone please assist me in identifying where the problem lies? I have experimented with adjusting the positioning of the xhr.open and .send requests but continue to receive error notifications. My suspicion is that the issue may be related to the .send() request?
//Vanilla JS AJAX request to get species from JSON file & populate Select box
function getJSON(path,callback) {
var xhr = new XMLHttpRequest(); //Creating a new request instance
xhr.open('GET', path ,true); //Preparing asynchronous GET request
xhr.send(); //Sending the request
xhr.onreadystatechange = function(){ //Checking every change in ready state (0-4)
if (xhr.readyState === 4) { //Upon completion of request and response readiness
if (xhr.status === 0 || xhr.status === 200) { //Ensuring status is OK (local file or server)
var data = JSON.parse(xhr.responseText); //Parsing returned JSON string
if (callback) {callback(data);} //Executing callback on returned data, if specified
}
}
};
}
//-----------------------------------------------------------------------------
//Testing execution of above function with callback
getJSON('js/species.json', function(data){
console.log(data);
});
The following error has been raised in the Chrome console:
"XMLHttpRequest cannot load file:///C:/Users/brett/Desktop/SightingsDB/js/species.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource."
I would greatly appreciate any insights into this matter. Thank you.