I am trying to create a function that returns the contents of a txt file using JavaScript so it can be stored in a variable and used at a later time. So far I have tried:
var text;
function getText(url) {
fetch(url)
.then( r => r.text() )
}
getText("foo.txt").then(r => text);
but this says that text is undefined.
I have also tried:
function getText(url) {
var client = new XMLHttpRequest();
client.open('GET', url);
client.onreadystatechange = function() {
text = client.responseText;
return text;
}
client.send();
}
This still gives me undefined. If I put a console.log()
inside the readystatechange
it gives the right text but repeats it twice.
I have also tried:
function getText(url) {
jQuery.get(url, function(data) {
console.log(data);
});
return data;
}
but this gives me an error saying jquery is not defined
and I can't seem to get jQuery to work so preferably is there anyway to do this without jquery?