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:
def fileContents = 'http://localhost/foo.txt'.toURL().text;
println fileContents;
How can I get a similar result in javascript?
When working with jQuery, instead of using
jQuery.get
, e.g.you could use
.load
which gives you a much more condensed form:.load
gives you also the option to load partial pages which can come in handy, see api.jquery.com/load/.This should work in almost all browsers:
Additionally, there's the new
Fetch
API:here is how I did it in jquery:
If you only want a constant string from the text file, you could include it as JavaScript:
The string loaded from the file becomes accessible to JavaScript after being loaded. The `(backtick) character begins and ends a template literal, allowing for both " and ' characters in your text block.
This approach works well when you're attempting to load a file locally, as Chrome will not allow AJAX on URLs with the
file://
scheme.One thing to keep in mind is that Javascript runs on the client, and not on the server. You can't really "load a file" from the server in Javascript. What happens is that Javascript sends a request to the server, and the server sends back the contents of the requested file. How does Javascript receive the contents? That's what the callback function is for. In Edward's case, that is
and in danb's case, it is
This function is called whenever the data happen to arrive. The jQuery version implicitly uses Ajax, it just makes the coding easier by encapsulating that code in the library.
Using Fetch:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API