I'm trying to read multiple JSON files using code from this post:
Reading multiple files with Javascript FileReader API one at a time
Contents of the 2 JSON files Nathan.json
and Charles.json
are:
{"name": Nathan, "age": 24,"title": "Product Consultant"}
{"name": Charles, "age": 31, "title": "software engineer"}
I defined a global variable myOutput
to store the output, but it would not be passed outside of the function. To demonstrate I first log myOutput
in the function:
<html>
<head>
<title>
This is the JSON test.
</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<input type="file" id="filesx" name="filesx[]" onchange="readmultifiles(this.files)" multiple=""/>
<div id="bag"><ul/></div>
<script>
// define the global variable to store the function output
var myOutput = [];
window.onload = function()
{
if (typeof window.FileReader !== 'function')
{
alert("The file API isn't supported on this browser yet.");
}
}
function readmultifiles(files) {
var ul = document.querySelector("#bag>ul");
while (ul.hasChildNodes()) {
ul.removeChild(ul.firstChild);
}
function setup_reader(file)
{
// name of the file, nothing to do with its actual content
var name = file.name;
var reader = new FileReader();
reader.onload = function(e)
{
var bin = e.target.result; //get file content
// push the content into the global variable
myOutput.push(bin);
// create the text displayed after uploading the files
var li = document.createElement("li");
li.innerHTML = name + '<br />' + bin;
ul.appendChild(li);
console.log(myOutput);
}
reader.readAsBinaryString(file);
}
for (var i = 0; i < files.length; i++)
{
setup_reader(files[i]);
}
}
</script>
</body>
</html>
It worked and logged:
But if I move the log outside of the function:
......
ul.appendChild(li);
}
reader.readAsBinaryString(file);
console.log(myOutput);
}
for (var i = 0; i < files.length; i++)
{
setup_reader(files[i]);
}
}
</script>
......
The log information becomes:
Why does this happen and how can I pass the variable outside of the function?
Thanks!