-2

I have problem with JSON, I need to include JSON data into HTML, now, when I view source on page - #content is empty - but data is viewing, and I need to have this data parsed in HTML (hardly) to work with them

How do to solve that?

$(document).ready(function () {
    $.getJSON('data.json', function (data) {
        $('#content').empty();
        $.each(data, function (entryIndex, entry) {
            var html = '<div class="data" id="' + entry['number'] + '">';
            html += '<b>' + entry['number'] + '</b>';
            html += '<div class="product">' + entry['product'] + '</div>';
            html += '<div class="price">' + entry['price'] + ' eur</div>';
            html += '<section class="image"><img alt="' + entry['product'] + '" src="' + entry['image'] + '"/></section>';
            if (entry['ingredients']) {
                html += '<section class="ingredients">';
                html += '<ul>';
                $.each(entry['ingredients'], function (colorIndex, ingredients) {
                    html += '<li>' + ingredients + '</li>';
                });
                html += '</ul>';
                html += '</section>';
            }
            $('#content').append(html);
        });
    });
    return false;
});
Jamie Taylor
  • 4,709
  • 5
  • 44
  • 66

1 Answers1

0

Declare the html variable outside $.each() and put below line outside $.each():

$('#content').append(html);

And also, close your <div> after IF condition

 var html = '';
 $.each(data, function(entryIndex, entry){
        html += '<div class="data" id="' + entry['number'] + '">';                     
        html += '<b>' + entry['number'] + '</b>';
        html += '<div class="product">' + entry['product'] + '</div>';  
        html += '<div class="price">' + entry['price'] + ' eur</div>';              
        html += '<section class="image"><img alt="' + entry['product'] + '" src="' + entry['image'] + '"/></section>';
        if(entry['ingredients']){
            html += '<section class="ingredients">';                                            
            html += '<ul>';
            $.each(entry['ingredients'],function(colorIndex, ingredients){
                html += '<li>' + ingredients + '</li>';                        
            }); 
            html += '</ul>';                        
            html += '</section>';
        }
        html += '</div>';
    });  
   $('#content').append(html);
Rajesh
  • 3,743
  • 1
  • 24
  • 31