len*_*elt 5 javascript ajax json
我正在尝试使用 vanilla JS AJAX 请求从本地存储的 JSON 文件中拉回 JSON 字符串(特别是尝试不使用 JQuery) - 以下代码基于 此答案-但我在 Chrome 控制台中不断收到错误消息(见下文)。任何想法我哪里出错了?我尝试更改 xhr.open 和 .send 请求的位置,但仍然收到错误消息。我怀疑问题出在 .send() 请求上?
//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);
});
Run Code Online (Sandbox Code Playgroud)
Chrome 中的控制台抛出此错误:
“XMLHttpRequest 无法加载 file:///C:/Users/brett/Desktop/SightingsDB/js/species.json。跨源请求仅支持以下协议方案:http、data、chrome、chrome-extension、https、chrome-扩展资源。”
将不胜感激任何见解 - 非常感谢。