$.get-json数组复制


$.get json array duplicating

这是我的产品索引脚本。它多次生成相互叠加的产品索引。一层是固定的,另一层是可滚动的。我试过更改参数等,但当我这样做时,我无法显示内容。

有人能帮我吗?

<h3 class="title">PRODUCTS</h3> <br><br><br><br>

<script>
$.getJSON("products2.php", function(data){
  $.each(data, function(i, field){
    $("DIV").append("<div class='productBox'>" + "id: " + field[0] + "<br> <b>" + "Name: "+ field[1] + "</b> <br>" +  "Description: " + field[2] + "<br>" + "Price: £" + field[3] + "<br>"+ "Stock: " + field[4] + "<br>" + "</div>");
  });
});

</script>

<?php include 'footer.php';?>

您使用jQuery创建了一个div,但没有将其添加到DOM中。在html中添加一个容器,用于存储产品,例如…

<div id="ProductsContainer"></div>

然后在getJSON请求回调中,您可以清除容器并将新产品添加到其中

$('#ProductsContainer').html(''); //clear the html
$.each(data, function(i, field) {
    $('#ProductsContainer').append('your html'); //append new products
}

您确定要追加field[0]而不是类似以下内容:field.id或data[i].id吗?