I have a JSON file on my local computer and I want to read its contents and display it on the web browser by using pure javascript. Anything which refers to the server side will not work for me. It is required to be done purely on the Client Side. What are the possible solutions ? Note: ajax and anything related to that should not be used.
Asked
Active
Viewed 1.6k times
3
-
Check out this [link](https://stackoverflow.com/questions/7346563/loading-local-json-file) – cookiedough Jun 08 '17 at 14:33
-
I want to do it on the client side only with pure javascript and getJSON internally used ajax. First read this and then go somewhere else - http://api.jquery.com/jquery.getjson/ Also, before downvoting any question, just think about it, there are people who just don't accept what everybody says, they are also running there minds. – Devesh Jagwani Jun 08 '17 at 18:01
-
Maybe the author is asking not to use any JS library. Just pure Javascript. – d.i.joe Jul 09 '18 at 14:15
2 Answers
7
If you don't wanna do an ajax
to load the file, and let user select the file what he wanna load by <input type='file' />
, maybe this way is working for you.
document.getElementById('show').addEventListener('click', function() {
var file = document.getElementById('myfile').files[0];
var reader = new FileReader();
reader.readAsText(file, 'UTF-8');
reader.onload = function(evt) {
document.getElementById('content').innerHTML = evt.target.result;
}
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input type="file" name="" id="myfile">
<div id="content"></div>
<button id="show">Show</button>
</body>
</html>

Richard de Wit
- 7,102
- 7
- 44
- 54

Lai32290
- 8,062
- 19
- 65
- 99
1
function readFile(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4) {
if(rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
var value = JSON.stringify;
// now display on browser :)
}
}
}
rawFile.send(null);
}
readTextFile("file:///C:/your/path/to/file.txt");

Nicolò Boschi
- 138
- 7
-
I have seen this. You must have copied it,and by the way XMLHttpRequest should not be used as I have to do it purely on client side – Devesh Jagwani Jun 08 '17 at 17:51