简体   繁体   English

xmlHttpRequest 从项目文件夹中获取 json 文件

[英]xmlHttpRequest to get json file from project folder

"Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https." “跨源请求仅支持协议方案:http、data、chrome、chrome-extension、https。” always shows this whenever i tried to get json file through xmlHttpResuest.每当我尝试通过 xmlHttpResuest 获取 json 文件时,总是会显示这一点。 I have my project on my hard disk.我的硬盘上有我的项目。 There is a.json file at the same folder where html,js,css files are.在 html,js,css 文件所在的同一文件夹中有一个 .json 文件。 I run this project directly from the server.我直接从服务器运行这个项目。 I need to get the json file from that html page using xmlHttpRequest.我需要使用 xmlHttpRequest 从 html 页面获取 json 文件。 I can not use any local server.我不能使用任何本地服务器。

function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
    if (rawFile.readyState === 4 && rawFile.status == "200") {
        callback(rawFile.responseText);
    }
}
rawFile.send(null);
}


readTextFile("Game/test.json", function(text){
var data = JSON.parse(text);
console.log(data);

}); });

If you are using VS Code as code editor consider installing extension called live-server and start/run your application on this server.如果您使用 VS Code 作为代码编辑器,请考虑安装名为 live-server 的扩展程序并在此服务器上启动/运行您的应用程序。 It support file changes detection and CORS enabled.它支持文件更改检测并启用 CORS。

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

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