javascript
  • jquery
  • json
  • getjson
  • 2013-12-10 108 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"); 
    }); 
    
    相关问题