To read a file, use FileReader , which enables you to read the content of a File object into memory. You can instruct FileReader to read a file as an array buffer, a data URL, or text.
To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file.
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.
here is how I did it in jquery:
jQuery.get('http://localhost/foo.txt', function(data) {
alert(data);
});
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
If you only want a constant string from the text file, you could include it as JavaScript:
// This becomes the content of your foo.txt file
let text = `
My test text goes here!
`;
<script src="foo.txt"></script>
<script>
console.log(text);
</script>
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.
const response = await fetch('http://localhost/foo.txt');
const data = await response.text();
console.log(data);
Note that await
can only be used in an async
function. A longer example might be
async function loadFileAndPrintToConsole(url) {
try {
const response = await fetch(url);
const data = await response.text();
console.log(data);
} catch (err) {
console.error(err);
}
}
loadFileAndPrintToConsole('https://threejsfundamentals.org/LICENSE');
This should work in almost all browsers:
var xhr=new XMLHttpRequest();
xhr.open("GET","https://12Me21.github.io/test.txt");
xhr.onload=function(){
console.log(xhr.responseText);
}
xhr.send();
Additionally, there's the new Fetch
API:
fetch("https://12Me21.github.io/test.txt")
.then( response => response.text() )
.then( text => console.log(text) )
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
client.onreadystatechange = function() {
and in danb's case, it is
function(data) {
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With