使用XMLHttpRequest时,Javascript通过作用域保存变量

时间:2013-02-02 11:52:08

标签: javascript scope xmlhttprequest

var mapFile = new XMLHttpRequest();
mapFile.open("GET", "http://localhost:8000/res/map01.txt", true);

mapFile.onreadystatechange = function() {
  if (mapFile.readyState === 4) {
    if (mapFile.status === 200) {
      this.lines = mapFile.responseText.split("\n");
    }
  }
}

this.lines = mapFile.onreadystatechange.lines;

mapFile.send(null);

我有该代码,我正在尝试将this.lines保存在mapFile.onreadstatechange内,以便稍后在外部范围内另存为this.lines。但是,mapFile.onreadystatachange.lines未定义,我无法保存该变量供以后使用。我甚至尝试使用element.innerHTML这是一个肮脏的黑客,但它也没有用。

1 个答案:

答案 0 :(得分:2)

这里有三个主要问题:

  1. this中的onreadystatechange与函数外部的this不同,因为函数中的this由函数的确定方式决定调用。更多关于我的博客:Mythical methods | You must remember this

  2. XHR调用异步(默认情况下),因此当您尝试在{{1}上方使用this.lines时,您的回调系统尚未被调用调用。 (即使有同步请求,因为该行 send之前,它仍然不会被设置。)

  3. sendmapFile.onreadystatechange.lines引用的函数对象上查找名为lines的属性。它与函数中定义的任何变量完全无关。

  4. 这是针对主要项目的更新:

    mapFile.onreadystatechange