I have a textfile (.txt) on a server. It contains only one word i.e. ON or OFF. How can i use JQuery or Pure Javascript to read that word from the file.
I am thinking along the lines of $.ajax.
You can't read a "local" text file with jQuery. jQuery has no access to the client-side filesystem.
A text file on a server can be read with Javascript by downloading the file with Fetch / XHR and parsing the server response as text. Note that the file needs be on the same domain. If the file is on a different domain, then proper CORS response headers must be present.
Yes JS can read local files (see FileReader()) but not automatically: the user has to pass the file or a list of files to the script with an html <input type="file"> . Then with JS it is possible to process (example view) the file or the list of files, some of their properties and the file or files content.
The jQuery code uses getJSON() method to fetch the data from the file's location using an AJAX HTTP GET request. It takes two arguments. One is the location of the JSON file and the other is the function containing the JSON data. The each() function is used to iterate through all the objects in the array.
You could use the $.get
method to send a GET AJAX request to a resource located on the server:
$.get('/foo.txt', function(result) {
if (result == 'ON') {
alert('ON');
} else if (result == 'OFF') {
alert('OFF');
} else {
alert(result);
}
});
You can use $.get
to grab the content of that file, and then take action based on the data returned:
$.get('/path/to/file.txt',function(data) {
if (data == "ON") {
} else {
}
});
You can also use this file as a config (for future development) and keep there more informations, for example:
yourfile.txt:
{"enable":"ON","version":"1.0"}
and additionally use JSON
to parse file content:
$.get('/path/yourfile.txt', function(data) {
var config = JSON.parse(data);
if(config.enable == 'ON') {
// ...
} // ...
if(config.version == '1.0') {
// ...
} // ...
});
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