发布
社区首页 >问答首页 >JSON使用JavaScript读取本地文件(类似问题堆栈溢出没有帮助)

JSON使用JavaScript读取本地文件(类似问题堆栈溢出没有帮助)
EN

Stack Overflow用户
提问于 2015-09-04 07:17:42
回答 3查看 397关注 0票数 0

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

代码语言:javascript
代码运行次数:0
复制
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无法加载file:///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

XMLHttpRequest未捕获:未能对“”XMLHttpRequest“”执行“”JSON.js:36“”:未能加载'file:///C:/Practice/CMPE%20273%20refresher/json/Sample.json'.“”

EN

回答 3

Stack Overflow用户

发布于 2015-09-04 07:22:49

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

有许多nodejs服务器可供选择,您也可以安装lightweight或xampp/wampp服务器。

票数 1
EN

Stack Overflow用户

发布于 2015-09-04 14:17:51

嘿,你的网址不正确。请参考这个

xmlhttp.open("GET",url,true);

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

代码语言:javascript
代码运行次数:0
复制
method: the type of request: GET or POST
url: the location of the file on the server
async: true (asynchronous) or false (synchronous)
票数 0
EN

Stack Overflow用户

发布于 2016-12-07 09:03:45

如果您使用的是兼容的HTML5浏览器,则可以使用FileReader应用编程接口。

请参阅https://stackoverflow.com/a/40946430/2476389

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32386862

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档