json数组仅填充第一个值

时间:2012-11-02 18:47:01

标签: jquery asp.net json

嗨,我有一个本地文件的问题,它存储了一些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>');
        });
    });
});​

所以不是输出作为罗马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" 
        }
            ]                       

}

1 个答案:

答案 0 :(得分:2)

JSON中缺少逗号

},  <-- Missing comma between two objects
 { 

你也是以错误的方式访问json ..你的json是一个对象数组

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

<强> Check Fiddle

enter image description here

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

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

<强> Fiddle Bracket Notation

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

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

}

<强> For Fiddle