Loading Text File Contents into a JavaScript Variable
Question: How can we load the contents of a local text file (foo.txt) into a JavaScript variable, similar to doing so in Groovy?
Solution:
XMLHttpRequest (AJAX without XML) provides a way to retrieve remote resources asynchronously, enabling us to read the text file's contents via the following steps:
var client = new XMLHttpRequest();
client.open('GET', '/foo.txt'); client.send();
client.onreadystatechange = function() { // Alert the responseText when the request is complete. if (client.readyState == 4 && client.status == 200) { alert(client.responseText); } }
Alternative Option - jQuery:
While using XMLHttpRequest works, jQuery offers a more convenient interface for AJAX operations:
$.ajax({ url: '/foo.txt', dataType: 'text', success: function(data) { console.log(data); } });
Note:
For security reasons, this approach only allows loading files from the same domain as the application's origin.
The above is the detailed content of How to Load a Local Text File into a JavaScript Variable?. For more information, please follow other related articles on the PHP Chinese website!