I'm facing an issue where I have a .txt file accessible via http (for example, "", although not an actual link) and I am attempting to load it into a JavaScript array by lines using pure JavaScript. However, none of the solutions provided by others seem to be working for me. The explanations are unclear or insufficient for me to make necessary modifications.
Here are two solutions that I have come across which claim to work with raw JavaScript:
var openFile = function(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function(){
var dataURL = reader.result;
var output = document.getElementById('output');
output.src = dataURL;
};
reader.readAsDataURL(input.files[0]);
};
and
function readTextFile(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function () {
if(rawFile.readyState === 4) {
if(rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
However, neither of these solutions actually returns the text content of the file in an array format where each cell represents an individual line from the text file. How can I achieve this?
EDIT: I tried modifying the second option as follows:
function readTextFile(file){
var allText;
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function () {
if(rawFile.readyState === 4) {
if(rawFile.status === 200 || rawFile.status == 0) {
allText = rawFile.responseText.split("\n");
return allText;
}
}
}
rawFile.send(null);
}
Unfortunately, I encountered two errors:
Content Security Policy: Ignoring ‘x-frame-options’ because of ‘frame-ancestors’ directive.
and
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://foo.net/bar.txt. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Upon debugging, I discovered that the program doesn't even reach the onreadystatechange
section.