0

嗨,我对存储一些 json 数据的本地文件有疑问

{
  "tournament": [{
    "TeamName": "AS Roma",
    "TeamPlayer": "Rickard"
  } {
    "TeamName": "Inter",
    "TeamPlayer": "Bobban"
  }]
}​

然后在buttonclick上我尝试用这个数据填充一个数组。但它只需要“AS Roma”和“Rickard”而不是“As Roma”“Rickard”和“Inter”“Bobban”。

// Get teams
var url = "http://localhost:57608/json/teams.txt";
$("#btnGetTeams").on('click', function() {
    var allItems = [];
    $.getJSON(url, function(data) {
        $.each(data, function(i, team) {
            allItems.push({
                theTeam: team.tournament.TeamName,
                thePlayer: team.tournament.TeamPlayer
            });
        });
        $.each(allItems, function(i, val) {
            $('#teams').append('<p>' + val.theTeam + val.thePlayer + '</p>');
        });
    });
});​

因此,它不会输出 AS Roma Rickard Inter Bobban,而是只写 AS Roma Rickard。我究竟做错了什么?

感谢 Sushanth 更新完整的工作代码

// Get teams
var url = "http://localhost:57608/json/teams.txt";
$("#btnGetTeams").on('click', function () {
                var allItems = [];
                $.getJSON(url,
                         function (data) {                               
                                 $.each(data.tournament, function (i) {
                                     allItems.push({
                                         theTeam: data["tournament"][i]["TeamName"],
                                         thePlayer: data["tournament"][i]["TeamPlayer"],
                                     });
                                 });
                             $.each(allItems, function (i, val) {
                                 $('#teams').append('<p>' + val.theTeam + val.thePlayer + '</p>');
                             });                                 
                         });
            });

与 Json

{
"tournament": [
        {
            "TeamName": "AS Roma",
            "TeamPlayer": "Rickard" 
        },
        { 
            "TeamName": "Inter",
            "TeamPlayer": "Bobban" 
        }
            ]                       

}

4

1 回答 1

2

JSON 中缺少逗号

},  <-- Missing comma between two objects
 { 

此外,您以错误的方式访问 json .. 您的 json 是一个对象数组

$.each(data.tournament, function (i, team) {
       allItems.push({
                        theTeam : team.TeamName,
                        thePlayer: team.TeamPlayer
    });
}); 

检查小提琴

在此处输入图像描述

用括号表示法试试这种方式..

$.each(data.tournament, function(i) {
    allItems.push({
        theTeam: data["tournament"][i]["TeamName"],
        thePlayer: data["tournament"][i]["TeamPlayer"],
    });
});

小提琴括号符号

如果这不起作用,请使用 for 循环

var allItems = [];
var data = data.tournament;
var i = 0;
for(key in data){
     allItems.push({
        theTeam: data[i].TeamName,
        thePlayer: data[i].TeamPlayer,
    });

}

对于小提琴

于 2012-11-02T18:48:42.093 回答