Home >Web Front-end >JS Tutorial >How Can I Load a Text File\'s Contents into a JavaScript Variable?
You have a text file stored at the root of your web application and you wish to load its contents into a JavaScript variable. Similar to how you would utilize the 'toURL()' method in Groovy, you can leverage XMLHttpRequest (AJAX) to achieve this in JavaScript.
The implementation of AJAX is contingent upon the JavaScript framework you are using. However, disregarding interoperability concerns, your code structure would resemble the following using plain JavaScript:
const client = new XMLHttpRequest(); client.open('GET', '/foo.txt'); client.onreadystatechange = function() { alert(client.responseText); }; client.send();
AJAX, however, may not be universally accessible across all platforms. Therefore, it is advisable to utilize an AJAX framework like jQuery to ensure compatibility.
One crucial point to note is that this method will only be successful if the "foo.txt" file is hosted on the same domain as your web application. If it resides on a different domain, security policies will restrict you from accessing the file's content.
The above is the detailed content of How Can I Load a Text File\'s Contents into a JavaScript Variable?. For more information, please follow other related articles on the PHP Chinese website!