2016-07-14 56 views
0

我想将大量产品加载到从JSON文件中获取数据的页面部分。我已经得到它使用JavaScript的工作,但我宁愿使用jQuery。控制台中没有错误,但数据未加载。我正在使用Bootstrap。相对较新的Ajax/JSON。未使用jQuery加载JSON数据

HTML

<div class="cat-group"> 
    <div id="content"></div> 
</div 

CSS

.cat-group { overflow: hidden; } 

jQuery的

$(function(){ 

function loadProducts() {      
    $.getJSON('products.json')    
    .done(function(data){      
    products = data;        
    }).fail(function() {      
    $('#content').html('Sorry! We could not load our products at the moment. Try again later!'); 
}); 
} 

loadProducts();          

$(window).on('load', function(){ 

var newContent = '';        // Build up timetable by 
for (var i = 0; i < products.length; i++) {  // looping through events 
    newContent += '<div class="col-lg-3 col-md-4 col-xs-6">'; 
    newContent += '<a class="thumbnail">'; 
    newContent += '<h4>SKU: <span>' + products[i].product + '</span></h4>'; 
    newContent += '<img class="img-responsive" src="' + products[i].img + '">'; 
    newContent += '</a>'; 
    newContent += '</div>'; 
} 

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

    }); 

}) 

JSON文件

{ 
"products": [ 
{ 
"product": "product1", 
"price": "10", 
"sku": "1", 
"img": "img/prod-1.jpg" 
}, 
{ 
"product": "product2", 
"price": "12", 
"sku": "2", 
"img": "img/prod-2.jpg" 
}, 
{ 
"product": "product3", 
"price": "13", 
"sku": "3", 
"img": "img/prod-3.jpg" 
}, 
{ 
"product": "product3", 
"price": "14", 
"sku": "4", 
"img": "img/prod-4.jpg" 
} 
] 
} 
+0

打印/控制台登录您的数据 –

+0

@NitinDhomse所有对象出现在控制台 –

+0

那你怎么可以这样说数据不装? –

回答

1

我已经在你的代码的一些变化,试试这个

$(function(){ 

      function loadProducts() {      
       $.getJSON('products.json')    
       .done(function(data){      
        products = data.products; 
        renderProducts(); 
       }).fail(function() {      
        $('#content').html('Sorry! We could not load our products at the moment. Try again later!'); 
       }); 
      } 

      loadProducts();          


     }); 


     function renderProducts() { 

      var newContent = '';        // Build up timetable by 
      for (var i = 0; i < products.length; i++) {  // looping through events 
       newContent += '<div class="col-lg-3 col-md-4 col-xs-6">'; 
       newContent += '<a class="thumbnail">'; 
       newContent += '<h4>SKU: <span>' + products[i].product + '</span></h4>'; 
       newContent += '<img class="img-responsive" src="' + products[i].img + '">'; 
       newContent += '</a>'; 
       newContent += '</div>'; 
      } 

      $('#content').html(newContent); 
     } 
+0

谢谢!它的工作原理 –

+0

欢迎。请标记为正在工作:) –

0

你是治疗返回数据,就好像它是琳琅满目的产品,但它实际上是包含一系列的产品的对象。尝试 products = data.products;代替 产品=数据;

0

试试这个。只需将products = data替换为products = data.d;

$(function(){ 

function loadProducts() {      
    $.getJSON('products.json')    
    .done(function(data){      
    products = data.d;        
    }).fail(function() {      
    $('#content').html('Sorry! We could not load our products at the moment. Try again later!'); 
}); 
}