JavaScript:变量在函数外部无效?

时间:2017-06-06 21:56:44

标签: javascript json

为什么我不能调用我在函数内定义的变量?这是我的代码......

  var username;
  var rank;
  var steamid;
  var avatar;

  var xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {

        if (this.responseText == "null") {
        } else {
            var infoArr = JSON.parse(this.responseText);
            var username = infoArr.username;
            var rank = infoArr.rank;
            var steamid = infoArr.steamid;
            var avatar = infoArr.avatar;
            testIt();
      }
    }
};

xhr.open("GET", "../getInfo.php", true);
xhr.send();

function testIt() {
  alert(username);
}

函数testIt()返回:undefined

我的代码所做的是从JSON编码页面获取信息并生成变量。

1 个答案:

答案 0 :(得分:0)

如果要使用函数外部的变量,则需要在函数外部定义它们。

var username, rank, steamid, avatar, infoArr, username, rank, steamid, avatar;

  var xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {

        if (this.responseText == "null") {
        } else {
            infoArr = JSON.parse(this.responseText);
            username = infoArr.username;
            rank = infoArr.rank;
            steamid = infoArr.steamid;
            avatar = infoArr.avatar;
            testIt();
      }
    }
};

xhr.open("GET", "../getInfo.php", true);
xhr.send();

function testIt() {
  alert(username);
}