javascript - CORS error when accessing local JSON file using vanilla JS AJAX request? -
i trying use vanilla js ajax request pull json string locally stored json file (specifically trying not use jquery) - below code based on this answer - keep getting error in chrome console (see below). ideas i'm going wrong? have tried changing positioning of xhr.open & .send requests, still error messages. suspect issue lies .send() request?
//vanilla js ajax request species json file & populate select box function getjson(path,callback) { var xhr = new xmlhttprequest(); //instantiate new request xhr.open('get', path ,true); //prepare asynch request xhr.send(); //send request xhr.onreadystatechange = function(){ //everytime ready state changes (0-4), check if (xhr.readystate === 4) { //if request finished & response ready (4) if (xhr.status === 0 || xhr.status === 200) { //then if status ok (local file || server) var data = json.parse(xhr.responsetext); //parse returned json string if (callback) {callback(data);} //if specified, run callback on data returned } } }; } //----------------------------------------------------------------------------- //test execute above function callback getjson('js/species.json', function(data){ console.log(data); }); the console in chrome throwing error:
"xmlhttprequest cannot load file:///c:/users/brett/desktop/sightingsdb/js/species.json. cross origin requests supported protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource."
would grateful insights - many thanks.
try run application on local server apache or wamp not face issue
Comments
Post a Comment