我正在尝试使用原生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);
});
Chrome浏览器控制台报错如下:
"XMLHttpRequest无法加载file:///C:/Users/brett/Desktop/SightingsDB/js/species.json。跨域请求仅支持协议方案:http、data、chrome、chrome-extension、https、chrome-extension-resource。"
请问有什么解决方法吗?非常感谢。
file://
URL 视为不同的域。 - Pointy