2014-10-20 17 views
0

您好新手到JSON我不知道如何迭代JSON over $ .each函數我工作但它顯示總是顯示值爲undefined我不知道爲什麼它是jquery getJson方法爲複雜的json如何獲取值使用jquery每個方法

這裏的json看起來如何保存爲新的文件data.json

{ "users":[ 
      { 
       "firstName":"Ray", 
       "lastName":"Villalobos", 
       "joined": { 
        "month":"January", 
        "day":12, 
        "year":2012 
       } 
      }, 
      { 
       "firstName":"John", 
       "lastName":"Jones", 
       "joined": { 
        "month":"April", 
        "day":28, 
        "year":2010 
       } 
      } 
    ]} 

在這裏,我需要在JSON 與註冊日期迭代的名字,我迭代過來jQuery的通過像這樣

$(function(){ 
    $(document).on('click', '.users', function(e){ 
     e.preventDefault();            
     $.getJSON("js/data.json", function(data) { 
      var items = []; 
      $.each(data.users, function(key, val) { 
      console.log(data.users);       
      items.push("<li id='" + data.users.firstName + "'><span><p>" + data.users.firstName + "</p></span></li>"); 
      }); 
      $("<ul/>", { 
      "class": "users-lists", 
      html: items.join("") 
       }).appendTo(".nlst"); 
     }); 
    }); 
}); 

幫我出

回答

1

在jQuery代碼改變這一行

items.push("<li id='" + data.users.firstName + "'><span><p>" + data.users.firstName + "</p></span></li>"); 

items.push("<li id='" + val.firstName + "'><span><p>" + val.firstName + "</p></span></li>"); 

jQuery的文檔Here

+0

感謝我有和一個小疑問怎麼辦我遍歷'users'中的嵌套對象名爲'joined'? – Vikranth 2014-10-20 07:20:42

+0

您需要在$ .each循環內添加另一個$ .each循環。將值作爲參數傳遞給$ .each循環內部 – chandu 2014-10-20 07:21:55

+0

噢,是的,我的不幸感謝。 – Vikranth 2014-10-20 07:26:00