【问题标题】:xmlHttpRequest to get json file from project folderxmlHttpRequest 从项目文件夹中获取 json 文件
【发布时间】:2020-08-12 05:52:00
【问题描述】:

“跨源请求仅支持协议方案:http、data、chrome、chrome-extension、https。”每当我试图通过 xmlHttpResuest 获取 json 文件时,总是会显示这个。我有我的项目 我的硬盘。在 html、js、css 文件所在的同一文件夹中有一个 .json 文件。我直接从服务器运行这个项目。我需要使用 xmlHttpRequest 从该 html 页面获取 json 文件。我不能使用任何本地服务器。

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);

});

【问题讨论】:

  • 能否从控制台添加错误快照?
  • 说明已经够清楚了,没有服务器就不能使用XMLHttpRequest。

标签: javascript html xmlhttprequest


【解决方案1】:

如果您使用 VS Code 作为代码编辑器,请考虑安装名为 live-server 的扩展程序并在此服务器上启动/运行您的应用程序。它支持文件更改检测和启用 CORS。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-11
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 2020-12-13
    相关资源
    最近更新 更多