使用jQuery导航JSON会导致未定义的项

时间:2016-01-29 16:17:14

标签: jquery json

我想循环使用JSON中的一些数据。

{
    "data": [{
        "id": "1561",
        "companyName": "Keeley Furniture Limited",
        "lat": "51.50622110",
        "lng": "-0.10131790",
        "city": "London",
        "street1": "123 Waldorf St",
        "street2": null,
        "street3": "",
        "zip": "SE1 0SW",
        "country": "United Kingdom",
        "email": "aamir@dwelldf.co.uk",
        "profile": "http:\/\/craft.fira\/directory\/company\/1561\/keeley-furniture-limited",
        "businessCategories": []
    }, {
        "id": "1501", ...etc

到目前为止,我有这个:

$(function() {
     var $members = $('#memberlist');

     $.getJSON("/directory/JSON/fullmembers.json", function(memberlist) {
         console.log('success');
         var members = memberlist.data;
         $.each(members, function(member) {
             $members.append("<li>" + member["companyName"] + "</li>");
         });
    });
});

这导致大量<li>undefined</li>被附加到ul。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

each()处理程序函数中的第一个参数是数组中当前元素的索引。元素本身是第二个参数。试试这个:

$.getJSON("/directory/JSON/fullmembers.json", function(memberlist) {
     console.log('success');
     var members = memberlist.data;
     $.each(members, function(index, member) { // note the 'index' param here
         $members.append("<li>" + member["companyName"] + "</li>");
     });
});

Working example