【问题标题】:"Uncaught TypeError: Cannot read property 'x' of undefined" when trying to get a property from an object尝试从对象获取属性时“未捕获的类型错误:无法读取未定义的属性‘x’”
【发布时间】:2014-05-03 23:12:34
【问题描述】:

所以,我通过 Steam Web API 获得了 JSON 格式的 Steam 游戏列表。当我尝试直接通过 Chrome 控制台从 JSON 获取属性时,一切都很好。但是当我在代码中执行同一行时,它会抛出 Uncaught TypeError: Cannot read property 'x' of undefined('x' 代表我尝试获取的任何属性)。

key = "lotsofrandomnumbersandletters";
id = "steamprofileid";
var gameList = $.getJSON("http://www.corsproxy.com/api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=" + key + "&steamid=" + id + "&format=json");
var gameCount = gameList.responseJSON.response.game_count;

【问题讨论】:

    标签: javascript jquery json steam


    【解决方案1】:

    $.getJSON() 是异步的,您需要在回调中访问其结果...

    $.getJSON("http://www.corsproxy.com/api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=" 
            + key + "&steamid=" + id + "&format=json", function (gameList) {
        var gameCount = gameList.responseJSON.response.game_count;
    });
    

    【讨论】:

    • 我已将其更改为 var key = "XXXXXXXXXXXXXXXXXX"; var id = "XXXXXXXXXXXXXXXX"; $.getJSON("http://www.corsproxy.com/api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=" + key + "&steamid=" + id + "&format=json", function(gameList){ var gameCount = gameList.responseJSON.response.game_count; });,但仍然报错 (Cannot read property 'response'...)。我做错了什么?
    【解决方案2】:

    使用 Anthony 的答案解决了这个问题,但在 $.getJSON 之外声明了 gameCount

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-25
      • 2019-02-26
      • 2012-10-01
      • 2021-01-16
      • 1970-01-01
      • 2021-12-22
      • 2017-07-26
      相关资源
      最近更新 更多