简体   繁体   中英

How to use append with getJSON

I'm trying to display results from getJSON function inside

<ul>
<li> item 1 link</li>
<li> item 2 link</li>
<li>item 3 link  </li>
... etc.
</ul>

What I've tried is:

$.getJSON($URL, function(data) {
                var array = $.map(data, function(item) {
                    return {
                        title: item.title,
                        id: item.id
                    };
                });
                for (var i = 0; i < 11; i++) {
                    $('#related-sites').append("<li>"+array.title+"</li>");
                }
            });

But I've got an error "Undefined" :/ Please help!

I don't see as why do you need that $.map also why do you hard-code loop with index with magic values, also you missed index here array.title , try this instead:

$.getJSON($URL, function(data) {
  var iHtml = '';
  $.each(data, function(i, item) {
    iHtml += '<li>' + (item.title || '') + '</li>';
  });
  $('#related-sites').append(iHtml);
});

Edited:

I need to get only the first ten items

$.getJSON($URL, function(data) {
  var iHtml = '';
  $.each(data, function(i, item) {
    if(10 <= i) return false;
    iHtml += '<li>' + (item.title || '') + '</li>';
  });
  $('#related-sites').append(iHtml);
});

You are looking for property title of an array...not the specific items within the array

Change

$('#related-sites').append("<li>"+array.title+"</li>");

To

$('#related-sites').append("<li>"+array[i].title+"</li>");
                                    // ^^^

Beyond that your map seems redundant and you could just loop over the data itself and get same results

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM