简体   繁体   English

使用 vanilla JS AJAX 请求访问本地 JSON 文件时出现 CORS 错误?

[英]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).我正在尝试使用 vanilla JS AJAX 请求从本地存储的 JSON 文件中提取 JSON 字符串(特别是尝试不使用 JQuery) - 以下代码基于此答案- 但我在 Chrome 控制台中不断收到错误(见下文)。 Any ideas where I'm going wrong?任何想法我哪里出错了? I have tried changing the positioning of the xhr.open & .send requests, but still get error messages.我曾尝试更改 xhr.open 和 .send 请求的位置,但仍然收到错误消息。 I suspect the issue lies with the .send() request?我怀疑问题出在 .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);
});

The console in Chrome is throwing this error: Chrome 中的控制台抛出此错误:

"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." “XMLHttpRequest 无法加载 file:///C:/Users/brett/Desktop/SightingsDB/js/species.json。跨源请求仅支持以下协议方案:http、data、chrome、chrome-extension、https、chrome-扩展资源。”

Would be grateful for any insights - many thanks.将不胜感激任何见解 - 非常感谢。

Basically as Felix, error msg, et al below say - simply can't run an AJAX request against a local file.基本上就像 Felix、error msg 和下面所说的那样 - 根本无法对本地文件运行 AJAX 请求。

Thanks.谢谢。

尝试在 apache 或 wamp 等本地服务器上运行该应用程序,那么您将不会遇到任何问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM