Dirty Bird Design
Dirty Bird Design

Reputation: 5533

Create <ul> from JSON with jQuery

Spent better part of the afternoon on this, can't seem to get it exactly right. I have an external JSON file that looks like this:

[
    {
        "link": "http://www.google.com",
        "pName":"first partner",
        "vTitle":"Video Title",
        "shortDesc":"Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque iusto, culpa mollitia, esse nobis iure.",
        "longDesc":"Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas excepturi optio harum debitis, sed delectus nisi vel dicta, corporis corrupti, omnis ipsam quaerat. Nemo, voluptatum. Asperiores magnam, iste deleniti maxime. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Blanditiis, recusandae, quod. In assumenda, modi velit itaque enim sunt tempore eum, perspiciatis hic, vitae voluptas. Iste et sint odit molestiae illo."
    }
]

I need to create a li from each, and display it. Here's the closest I got, although its saying one of my items (link) isn't defined:

$(function(){
    $.getJSON('./JSON/latest.json', function(data) {
        var items = [];
        $.each(data, function(i, item) {
        items.push('<li><a href="' + link + '">' + pName + '</a><span class="vTitle">' + vTitle + '</span>' + shortDesc + '</li>');
        });
        $('#latestList').append( items.join('') );
    });
});

Upvotes: 0

Views: 595

Answers (3)

Joe
Joe

Reputation: 2596

The context is 'item' so you need to read the properties from that.

$(function(){
  $.getJSON('./JSON/latest.json', function(data) {
    var items = [];
    $.each(data, function(i, item) {
      items.push(
        '<li>' +
          '<a href="' + item.link + '">' + item.pName + '</a>' +
          '<span class="vTitle">' + item.vTitle + '</span>' +
          item.shortDesc +
        '</li>');
    });
    $('#latestList').append( items.join('') );
  });
});

Upvotes: 3

user2226112
user2226112

Reputation:

Instead of link and pName and so on

item[0].link
item[0].pName
item[0].vTitle
item[0].shortDesc

Upvotes: 0

B W
B W

Reputation: 702

I think you need to specify item.link.

Upvotes: 1

Related Questions