There is a function that should return the text from the file.

//Функция возращает текст из файла nameTextFile function fileProcess() { var xhr = new XMLHttpRequest(); xhr.open('GET', nameTextFile, true); xhr.send(); xhr.onreadystatechange = function () { if (this.readyState != 4) return; // по окончании запроса доступны: // status, statusText // responseText, responseXML (при content-type: text/xml) if (this.status != 200) { // обработать ошибку alert('ошибка: ' + (this.status ? this.statusText : 'запрос не удался')); return; } // получить результат из this.responseText или this.responseXML } //alert('готово'); DataFirm = (xhr.responseText); return DataFirm;; } 

So, it returns empty, but if you turn on the alert before the responseText line, then everything returns normally. What could be the reason? I understand the whole thing is that the alert stops the code and waits for the OK to be pressed, at this time all that is needed is loaded. But I don’t need an alert at all.

  • since you have a synchronous return, and asynchronous is required. See developer.mozilla.org/ru/docs/Web/API/XMLHttpRequest/… - Sublihim
  • true change to false in open() . - Visman
  • According to xmlhttprequest.ru , I just have asynchronous (TRUE), synchronous (false) does not seem to advise. Or did I get it all wrong? switched to false and earned. - Nykolay Ryzhov
  • @NykolayRyzhov, your request is asynchronous, but you get the answer synchronously! For this reason, the data from the server do not have time to come to a variable. Either make the request synchronous, or get the answer asynchronously. - Visman
  • I figured out the question, it might be useful for someone, really, when an asynchronous request, the program continues to go its own way without waiting for an answer, and if by that time the variable has not received data from the file, they will be extracted by default. In this case, the worst thing is that if the answer comes on time, then it seems that everything works fine until there is a delay. It will be correct not to transfer the given to the global variable, but to call the subsequent actions from this subroutine. Although this again, we transfer the call to synchronous mode. - Nykolay Ryzhov

0