【发布时间】:2015-09-24 23:17:45
【问题描述】:
我正在尝试使用 vanilla JS AJAX 请求从本地存储的 JSON 文件中拉回 JSON 字符串(特别是尝试不使用 JQuery)-以下代码基于 this answer-但我不断收到错误消息在 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。”
将不胜感激任何见解 - 非常感谢。
【问题讨论】:
-
这是一个安全问题,尝试在你的localhost服务器或现场运行它
-
错误信息有什么不清楚的地方?它明确表示
file协议不支持 CORS。 -
现代浏览器将每个
file://URL 视为不同的域。 -
显然,您是直接从文件系统运行脚本,而不是从 HTTP 服务器。 (正如@Özgür Ersil 建议的那样)
-
您根本无法向本地文件系统发出 Ajax 请求。
标签: javascript ajax json