I need to load json from local filesystem. This is what I tried:
index.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:
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:
[{"name" : "Harry", "age" : "32"}]
But nothing cant be read on console.log output. I tried with XMLHttpRequest()
function but soon realised it is only for web based json files. 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. You'll need to serve the file over HTTPS (through a backend server) or take a different approach to your overall problem.
I assume with 'local file system' you mean a local installed server like xampp?, In that case: - maybe you like to keep it simple:
<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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.