javascript
  • jquery
  • json
  • getjson
  • 2013-12-10 126 views 0 likes 
    0

    我嘗試訪問使用getJson的對象數組,我試過很多東西,但我不斷收到'未定義'或[對象,對象]返回。遍歷jQuery JSON對象數組

    $.getJSON("js/test.json", function(data) { 
        var items = new Array(); 
        $.each(data, function(key, val) { 
         items.push("<li id='" + key + "'>" + val.entries.title + "</li>"); 
        }); 
    
        $("<ul/>", { 
         "class": "my-new-list", 
         html: items.join("") 
        }).appendTo("body"); 
    }); 
    

    這裏是JSON,我試圖獲得每個'條目'的'標題'。

    { 
    "$xmlns": { 
        "pl1": "url" 
    }, 
    "startIndex": 1, 
    "author": "MJS", 
    "entries": [ 
        { 
         "title": "This is target", 
         "m$ct": [ 
          { 
           "m$name": "name" 
          } 
         ], 
         "m$rt": "pd", 
         "m$content": [ 
          { 
           "plfile$width": 640 
          }, 
          { 
           "plfile$width": 960 
          } 
         ], 
         "plm$c": [], 
         "link": "" 
        }, 
        { 
         "title": "title2", 
         "m$ct": [ 
          { 
           "m$name": "name" 
          } 
         ], 
         "m$rt": "pd", 
         "m$content": [ 
          { 
           "plfile$width": 640 
          }, 
          { 
           "plfile$width": 960 
          } 
         ], 
         "plm$c": [], 
         "link": "" 
        } 
    ] 
    } 
    
    +3

    看起來像你應該b迭代'data.entries'而不是'data'。那麼你會使用'val.title'而不是'val.entries.title'。不知道你期待什麼'li'的ID。如果這應該是索引號,那麼在那裏'鍵'就可以了。 –

    +0

    ...謝謝。就是這樣! – Randall987

    +0

    僅供參考,您可以使用'$ .map'來更加乾淨地構建陣列。這裏有一個演示:http://jsfiddle.net/Bxrnq/ –

    回答

    2
    $.each(data, function(key, val) { 
        items.push("<li id='" + key + "'>" + val.entries.title + "</li>"); 
    }); 
    

    應改爲閱讀:

    $.each(data.entries, function(key, entry) { 
        items.push("<li id='" + key + "'>" + entry.title + "</li>"); 
    }); 
    
    0

    你遍歷整個JSON,而不是條目

    應當在每個data.entries,然後就VAL .title

    $.getJSON("js/test.json", function(data) { 
        var items = new Array(); 
        $.each(data.entries, function(key, val) { 
         items.push("<li id='" + key + "'>" + val.title + "</li>"); 
        }); 
    
        $("<ul/>", { 
         "class": "my-new-list", 
         html: items.join("") 
        }).appendTo("body"); 
    }); 
    
    相關問題