2016-07-14 58 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!'); 
}); 
}