[英]reading local JSON file with javascript
I need to load json from local filesystem.我需要从本地文件系统加载 json。 This is what I tried:
这是我尝试过的:
index.htlm:索引.htlm:
<html>
<head>
<title>JSON File Locally by Javascript Without JQuery</title>
<script type="text/javascript" src="script.js"></script>
</head>
<body onload="loadJSON()">
Load JSON File Locally by Javascript Without JQuery
</body>
</html>
script.js:脚本.js:
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'employee.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
}
xobj.send(null);
}
loadJSON(function(response) {
jsonresponse = JSON.parse(response);
console.log(jsonresponse[0].name);
});
employee.json:员工.json:
[{"name" : "Harry", "age" : "32"}]
But nothing cant be read on console.log output.但是在console.log output上什么都读不出来。 I tried with
XMLHttpRequest()
function but soon realised it is only for web based json files.我尝试使用
XMLHttpRequest()
function 但很快意识到它仅适用于基于 web 的 json 文件。 Any help is appreceated.任何帮助表示赞赏。
What you're asking for simply isn't possible- browsers do not give javascript access to the filesystem for security reasons.您所要求的根本不可能 - 出于安全原因,浏览器不会让 javascript 访问文件系统。 You'll need to serve the file over HTTPS (through a backend server) or take a different approach to your overall problem.
您需要通过 HTTPS(通过后端服务器)提供文件,或者对您的整体问题采取不同的方法。
I assume with 'local file system' you mean a local installed server like xampp?, In that case: - maybe you like to keep it simple:我假设“本地文件系统”是指本地安装的服务器,例如 xampp?,在这种情况下:-也许您想保持简单:
<script>
window.onload = function(){
function loadJson(){
const xobj = new XMLHttpRequest();
xobj.open('POST', 'employee.json');
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
let data = xobj.responseText;
data = JSON.parse(data);
console.log(data[0]['name']);
}
}//xobj.onreadystatechange
xobj.send(null);
}
loadJson();
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.