I have a text file in the root of my web app http://localhost/foo.txt and I\'d like to load it into a variable in javascript.. in groovy I would do this:
XMLHttpRequest, i.e. AJAX, without the XML.
The precise manner you do this is dependent on what JavaScript framework you're using, but if we disregard interoperability issues, your code will look something like:
var client = new XMLHttpRequest(); client.open('GET', '/foo.txt'); client.onreadystatechange = function() { alert(client.responseText); } client.send();
Normally speaking, though, XMLHttpRequest isn't available on all platforms, so some fudgery is done. Once again, your best bet is to use an AJAX framework like jQuery.
One extra consideration: this will only work as long as foo.txt is on the same domain. If it's on a different domain, same-origin security policies will prevent you from reading the result.
fetch('http://localhost/foo.txt')
.then(response => response.text())
.then((data) => {
console.log(data)
})
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
here is how I did it in jquery:
jQuery.get('http://localhost/foo.txt', function(data) {
alert(data);
});