2015-02-08 67 views
-1

我在我的JSON列表中有多個項目。我想遍歷它並將其顯示在我的頁面上。我似乎無法進入下一個對象。如何循環瀏覽JSON列表?

{ 
"room":[ 
    {"campusName":"A", 
    "buildingCode":"B", 
    "roomNumber":"208", 
    "times":["7-8", "9-10"] 
}], 

"room2":[ 
{"campusName":"C", 
    "buildingCode":"D", 
    "roomNumber":"208", 
    "times":["7-8", "9-10" 
]} 
]} 
$(document).ready(function(){ 
    $.getJSON("data.json", function(data){ 
    $.each(data.room, function(){ 
     for(var i = 0; i < data.length; i++){ 
      $("ul").append("<li>campus: "+this['campusName']+"</li><li>building: "+this['buildingCode']+"</li><li>times: "+this.times+"</li>"); 
     } 
    }); 
    }); 
}); 
+2

嘗試循環通過'data'而不是'data.room' – user1950929 2015-02-08 09:16:46

+0

您不會通過「JSON列表」循環,因爲沒有這樣的事情。您解析JSON **字符串(!)**,然後循環訪問您獲得的對象和數組。 – 2015-02-08 09:19:19

回答

2

$.each(data, ..) - >每個元素將是:

"room":[ 
    {"campusName":"A", 
    "buildingCode":"B", 
    "roomNumber":"208", 
    "times":["7-8", "9-10"] 
}] 

然後,this[0]將提供你需要來構建你的li對象:

$.each(data, function(){ 
      $("ul").append("<li>campus: "+this[0]['campusName']+"</li><li>building: "+this[0]['buildingCode']+"</li><li>times: "+this[0].times+"</li>"); 
    }); 

Fiddle

+0

感謝您的幫助! – minionhacking 2015-02-08 09:25:08

3

嘗試此

var list = ''; 

$.each(data, function (i, root) { 
    $.each(root, function (i, el) { 
    list += "<li>campus: " + this.campusName + "</li><li>building: " + this.buildingCode + "</li><li>times: " + this.times.join(' ') + "</li>"; 
    }); 
}); 

$('ul').html(list); 

Example

如果root's在陣列只有一個元素

var list = ''; 

$.each(data, function (i, root) { 
    list += "<li>campus: " + root[0].campusName + "</li><li>building: " + root[0].buildingCode + "</li><li>times: " + root[0].times.join(' ') + "</li>"; 
}); 

$('ul').html(list); 

Example