我正在尝试读取本地.JSON文件,并使用JSON.parse将其放入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无法加载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'.“”
发布于 2015-09-03 23:22:49
您正在使用file://
协议运行该脚本。您将无法使用此协议执行该请求。您需要安装http
服务器才能执行请求(即使它是您计算机中的所有内容)。
有许多nodejs服务器可供选择,您也可以安装lightweight或xampp/wampp服务器。
发布于 2015-09-04 06:17:51
嘿,你的网址不正确。请参考这个
xmlhttp.open("GET",url,true);
指定请求的类型、URL以及是否应异步处理请求。
method: the type of request: GET or POST
url: the location of the file on the server
async: true (asynchronous) or false (synchronous)
发布于 2016-12-07 01:03:45
如果您使用的是兼容的HTML5浏览器,则可以使用FileReader应用编程接口。
https://stackoverflow.com/questions/32386862
复制