AJAX JQuery |访问返回的对象数据

时间:2015-09-16 08:43:04

标签: javascript jquery json ajax object

我正在尝试访问我所做的Ajax调用中返回的数据。这是引用steam API并成功返回数据。我有控制台记录它来检查。每当我尝试访问数据时,我会获得未定义的控制台消息。

下面是我返回的JSON文件的片段

{
"playerstats": {
    "steamID": "Removed for SO",
    "gameName": "ValveTestApp260",
    "stats": [
        {
            "name": "total_kills",
            "value": 7642
        },
        {
            "name": "total_deaths",
            "value": 7349
        },
        {
            "name": "total_time_played",
            "value": 427839
        },
        {
            "name": "total_planted_bombs",
            "value": 341
        },

以下是我的ajax电话的代码

$.ajax({
    url: this.props.url,
    dataType: 'json',
    crossDomain: true,
    success: function(data) {
        console.log("success", typeof data);
        console.log(data.playerstats.stats.total_kills);
        console.log(data["playerstats"]["stats"]["total_kills"]);
    }.bind(this),
        error: function(xhr, status, err, data) {
        console.error(this.props.url, status, err.toString());
    }.bind(this)
});

我成功进入了成功功能,但它在控制台中显示以下内容

success object
Inline JSX script:21 undefined
Inline JSX script:22 undefined

我尝试访问数据的console.log行中出现了2个未定义的错误,我唯一能想到的就是我错误地访问了它们。

尝试

console.log(data.playerstats.stats.total_kills);
console.log(data["playerstats"]["stats"]["total_kills"]);

2 个答案:

答案 0 :(得分:1)

total_kills不是统计信息的属性,也不是stats中每个项目的属性,而是属性"name",你想要的统计数组中每个项目的属性"value"

$.ajax({
    url: this.props.url,
    dataType: 'json',
    crossDomain: true,
    success: function(data) {
        console.log("success", typeof data);
        data.playerstats.stats.forEach(function (stat) {
            console.log(stat.value);
        });
    }.bind(this),
        error: function(xhr, status, err, data) {
        console.error(this.props.url, status, err.toString());
    }.bind(this)
});

要仅获取"total_kills" 属性 "name"项,您可以使用此项:

var totalKillsObj = data.playerstats.stats.reduce(function(item) {
  return item.name === 'total_kills';
});

var totalKills = totalKillsObj.value;

答案 1 :(得分:1)

Demo Fiddle

var data = {
    "playerstats": {
        "steamID": "Removed for SO",
            "gameName": "ValveTestApp260",
            "stats": [{
            "name": "total_kills",
                "value": 7642
        }, {
            "name": "total_deaths",
                "value": 7349
        }, {
            "name": "total_time_played",
                "value": 427839
        }, {
            "name": "total_planted_bombs",
                "value": 341
        }]
    }
}
alert(data.playerstats.steamID);
data.playerstats.stats.forEach(function (stat) {
    alert(stat.name + ":" + stat.value);//property for stats are name and value
});