JSON使用JavaScript读取本地文件(类似的问题Stack overflow没有帮助)

JSON read a local file using JavaScript (similar questions Stack overflow didnt help)

本文关键字:Stack 问题 overflow 有帮助 读取 JavaScript 使用 文件 JSON      更新时间:2023-09-26

我正在尝试读取本地。JSON文件并使用JSON。将其放入Javascript数组中。任何其他示例代码也会有所帮助。我无法使用下面的代码,它无法加载本地文件。

var xmlhttp = new XMLHttpRequest();
//xmlhttp.overrideMimeType("application/json"); //this line also didnt help
var url = "sample.json";
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        testme(xmlhttp.responseText);
    }
};
xmlhttp.send(); 
function testme(response){
    var record = JSON.parse(response);
    var out = "<table>";
    for(var i = 0; i < record.length; i++) { //prints all the data to html
        out += "<tr><td>" +
        record[i].Name +
        "</td><td>" +
        record[i].City +
        "</td><td>" +
        record[i].Country +
        "</td></tr>";
    }
    out += "</table>";
    document.getElementById("dis").innerHTML = out;
}

出现以下错误

XMLHttpRequest无法加载文件:///C:/Practice/CMPE%20273%20refresher/json/Sample.json。跨域请求只支持协议方案:http, data, chrome, chrome-extension, https, chrome-extension-resource。transmit1 @ JSON.js:36transmit @ JSON.js:41onclick @ jsonweb.html:11

json .js:36 Uncaught NetworkError: Failed to execute 'send' on' XMLHttpRequest: Failed to load 'file:///C:/Practice/CMPE%20273%20refresher/json/Sample.json'.

您正在使用file://协议运行脚本。您将无法使用此协议执行该请求。您需要安装http服务器,以便能够执行请求(即使它是您计算机中的所有内容)。

有许多轻量级HTTP服务器可供选择,或者您可以安装nodejs或xampp/wampp服务器。

嘿,你的URL不正确。请参考

xmlhttp.open("GET" url,真的),

指定请求的类型、URL,以及是否应该异步处理请求。

method: the type of request: GET or POST
url: the location of the file on the server
async: true (asynchronous) or false (synchronous)

如果你使用的是兼容的HTML5浏览器,你可以使用FileReader API。
见https://stackoverflow.com/a/40946430/2476389