I have a small web application using JS. It lies locally and should also be used locally. Without PHP and other things.

Data is written to the local file (located in the same folder as index.html). The data itself is just one duble number (1 line and all).

How can I, in JS code, count this number into a variable? ajax, jquery and does not help. I need to bring this variable to alert() , and it displays to me either [Object object] or undefined . I already tried a bunch of ways from Google - nothing helped.

UP:

url: file: /// C: /Users/ROCKer/Desktop/test/index.html

 var t; $.ajax({ type: "GET", url: "1.txt", success: function(text) { t = text; }, error: function() { // An error occurred } }); alert(t); 
  • Interesting to see how you get the data from the file? the code would be shown - Arsen
  • @Arsen say that I can not get. ideas are already zero. - Wlad
  • one
    From the file from the browser can not be read. This is a security restriction. - Stepan Kasyanenko
  • show the code that brought you either a [Object object] or undefined - Grundy
  • 2
    @Wlad, if you can change the format of the data in the file, you can load it as js code by creating a script element, and passing it the path to the file in src. The file should have a valid js code, for example var a = 10 , in this case, after loading and executing the script, you can access the variable a and get the value 10 - Grundy

4 answers 4

  var t = ''; // мне больше нравится так fetch('./foo.txt') .then(res => res.text()) .then(data => { t = data; alert(t); }) .catch(err => { throw err; }); // но можно и так $.ajax({ type: 'GET', url: './foo.txt', dataType: 'text', mimeType: 'application/text', success: function(text) { t = text; alert(t); }, error: function(err) { throw err; } }); 
  • ajax does not work in the case of file:/// - Grundy
  • one
    @Grundy, I do not agree. Works. - eustatos
  • @eustatos and in what variable the file was written? How can I display this text in an alert for example? - Wlad
  • @Wlad, made changes to the code so that an alert is displayed - eustatos
  • @eustatos really depends on the browser. In chrome there will be an error, in edge and ff it seems to work. - Grundy

As far as I remember, JS does not allow working directly with files in the file system, like other PLs (Java, C ++, C #) because your code executes the browser and only it can reach the files (and that is not a fact) There is documentation And a great article with examples The basic idea is that in your index.html file you are preparing a form for selecting and loading a file and already through JS you read the information from the file.

There is another way to get information, this is a request to the server that will return this file to you, but you do not want to use PHP and so on :)

I hope helped.

  • In general, all in the cashier ... - Wlad

As @Grundy said

if you can change the format of the data in the file, you can load it as js code by creating a script element, and passing it the path to the file in src. The file must have a valid js code, for example var a = 10, in this case, after loading and executing the script, you can access the variable a and get the value 10

 .........text.txt var x = 10; ................. ....... основной js var fn; // переменная куда считаем наш файл // функция для чтения js внутри другого js function include(url) { var script = document.createElement('script'); script.src = url; document.getElementsByTagName('head')[0].appendChild(script); } function xyz(){ include("text.txt"); // подключим js и возьмем из него нашу переменную return x; } function моя_функция_которая_постоянно_должна_считывать_новые_данные(){ ....... xyz() .......... } 
  • well, this should not work at all, because appendChild Only adds a script, you can't know when to load it. You can add an onload handler for the script, and it will already get the result. More details about getting the result from the asynchronous function can be found here - Grundy
  • @Grundy can tell me how to delete this connected script in a similar way? the problem is that it connects and stays until the page reloads. and when the data was updated in it and I try to count them - the already irrelevant variable gives me (the var x was 10 was 20), and he continues to give me 10. - Wlad
  • it's enough just to call download again - the script loads again and the variable value is updated - Grundy
  • @Grundy so I do. but it is not updated. maybe you know what prevents it in Android WebView (everything works IDEALLY in the browser on your computer). - Wlad
  • It is necessary to debug, since this is a normal script, you can add console.log to it and see if it runs at all a second time or not. - Grundy

And if you save data in json format and then parse it:

 var url = "file.json"; var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.send(); xhr.onreadystatechange = function(){ if (xhr.readyState == 4) { if (xhr.status == 200) { var result = JSON.parse(xhr.responseText); } } }