Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

javascript - CORS error when accessing local JSON file using vanilla JS AJAX request?

I am trying to use a vanilla JS AJAX request to pull back a JSON string from a locally stored JSON file (specifically trying not to use JQuery) - the below code is based on this answer - but I keep getting an error in the Chrome console (see below). Any ideas where I'm going wrong? I have tried changing the positioning of the xhr.open & .send requests, but still get error messages. I suspect the issue lies with the .send() request?

//Vanilla JS AJAX request to get species from JSON file & populate Select box
function getJSON(path,callback) {

    var xhr = new XMLHttpRequest();                                         //Instantiate new request

    xhr.open('GET', path ,true);                                            //prepare asynch GET request
    xhr.send();                                                             //send request

    xhr.onreadystatechange = function(){                                    //everytime ready state changes (0-4), check it
        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 the returned JSON string
                if (callback) {callback(data);}                             //if specified, run callback on data returned
            }
        }
    };
}
//-----------------------------------------------------------------------------

//Test execute above function with callback
getJSON('js/species.json', function(data){
    console.log(data);
});

The console in Chrome is throwing this error:

"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."

Would be grateful for any insights - many thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Basically as Felix, error msg, et al below say - simply can't run an AJAX request against a local file.

Thanks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...