“未捕获的TypeError:在尝试从对象获取属性时无法读取未定义的属性'x'

时间:2014-05-03 23:12:34

标签: javascript jquery json steam

所以,我通过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;

2 个答案:

答案 0 :(得分:2)

$.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;
});

答案 1 :(得分:0)

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