使用香草JS AJAX请求访问本地JSON文件时出现CORS错误? [英] CORS error when accessing local JSON file using vanilla JS AJAX request?
问题描述
我正在尝试使用香草JS AJAX请求从本地存储的JSON文件中拉回JSON字符串(特别是尝试不使用JQuery)-以下代码基于
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);
});
Chrome中的控制台抛出此错误:
The console in Chrome is throwing this error:
"XMLHttpRequest无法加载文件:///C:/Users/brett/Desktop/SightingsDB/js/species.json.仅协议方案支持跨源请求:http,数据,chrome,chrome扩展名,https ,chrome-extension-resource."
"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.
推荐答案
基本上,正如Felix,错误消息(MSG)等在下面说的那样-根本无法针对本地文件运行AJAX请求.
Basically as Felix, error msg, et al below say - simply can't run an AJAX request against a local file.
谢谢.
这篇关于使用香草JS AJAX请求访问本地JSON文件时出现CORS错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!