JSON使用JavaScript读取本地文件(类似的问题Stack overflow没有帮助)
JSON read a local file using JavaScript (similar questions Stack overflow didnt help)
我正在尝试读取本地。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
- 在指令控制器中使用$attrs时出现问题
- 将PHP变量传递给jQuery时遇到问题
- Canvas Html5绘图应用程序,移动画布会导致重大问题
- 参数变量出现ngTable指令问题
- 剑道网格jQuery动画()问题
- 我的jQuery插件参数没有正确启动,遇到了问题
- Phonegap-(安卓/iphone)多个图像的图像库出现问题
- TableExport jquery插件:文件名和扩展名问题
- JavaScript Pub/Sub属性访问问题
- JavaScript异步问题
- 如何解决Yii中的页面刷新问题
- Safari(Mac OS)上的jQuery平滑滚动问题
- jqGrid树网格问题
- 使用正则表达式评估电子邮件地址时出现性能问题
- 如何消除代码中的未定义和其他问题
- JavaScript代码问题:我正在将对象转换为数组
- 三星智能电视应用程序;Brightcove示例应用程序远程控制问题
- 由于iframe导致的问题
- JSON使用JavaScript读取本地文件(类似的问题Stack overflow没有帮助)
- 安装MEAN stack的问题