在Javascript中将文本文件异步分配给变量

时间:2016-11-08 16:38:19

标签: javascript file asynchronous

我正在查看Benjamin Gruenbaum's answer,他在HTML正文中打印result。虽然他确实进行了广泛的讨论,他和其他有关如何工作的答案,但他们并没有直接回答这个问题,即如何从异步调用中返回响应?

据我了解,他(和我)希望能够返回结果并将其分配给变量,例如,或者将console.log()分配给函数foo之外。 这是代码:

      foo(function (result) {
        document.body.innerHTML = result;
      });

      function foo(callback) {
        httpRequest = new XMLHttpRequest();
        httpRequest.onreadystatechange = function () {
            if (httpRequest.readyState === 4) { // request is done
                if (httpRequest.status === 200) { // successfully
                    callback(httpRequest.responseText); // we're calling our method
                }
            }
        };
        httpRequest.open('GET', "someFile.json");
        httpRequest.send();
      }

我真正想要的是读取文件“someFile.json”并将相应的字符串存储在变量jsonString中,而不是将其分配给页面正文,这样我就可以在其他地方执行某些操作

1 个答案:

答案 0 :(得分:0)

如果这是您所追求的,您可以使用变量。请记住,变量只会在onreadystatechange执行并分配时获得值。

  var someFileContent;

  foo(function () {
    console.log(someFileContent);
  });

  function foo(callback) {
    httpRequest = new XMLHttpRequest();
    httpRequest.onreadystatechange = function () {
        if (httpRequest.readyState === 4) { // request is done
            if (httpRequest.status === 200) { // successfully
                someFileContent = httpRequest.responseText;
                callback(); // we're calling our method
            }
        }
    };
    httpRequest.open('GET', "someFile.json");
    httpRequest.send();
  }
相关问题