2012-11-02 53 views
0

嗨填充我有一個本地文件至極存儲問題的一些JSON數據JSON數組只獲取與第一個值

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

然後在buttonclick我嘗試填充這個數據的數組。但它只需要「羅姆人」和「裏卡德」而不是「羅姆人」「裏卡德」和「國際」「鮑勃班」。

// 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國際Bobban,它只寫AS羅馬Rickard。 我在做什麼錯?

更新完全工作代碼感謝舒尚特

// 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" 
     } 
      ]      

}

回答

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

+0

感謝察覺缺少逗號。雖然我試着改變代碼,就像你說的data.tournament。但現在我得不到輸出:/ – rickard

+0

檢查小提琴http://jsfiddle.net/sushanth009/77muQ/ –

+0

我可以看到小提琴演示一個工作的例子。但是,如果我這樣做,除了我還必須包括.getJson結果,我什麼也沒有。 – rickard