我正在使用 php cart 类,并添加了一些 jquery 来在用户单击添加产品时更新 div。
我遇到的问题是,当添加产品时,产品列表会在 html 页面(屏幕截图)上重复,尽管它不在源代码中。
默认页面:
<小时/>当添加任何产品时,结果如下:
<小时/>正如您所看到的,购物车已更新,但出现了一组重复的产品。
这是我正在使用的 JQuery:
<script type="text/javascript">
function getItem(id)
{
$.ajax({
type: "GET",
url: 'index2.php',
data: "action=add&id=" + id,
success: function(data) {
$('#info').html(data);
}
});
}
</script>
以及带有 id 信息的 div 之间的 PHP:
<div id="info">
<?php
if(!empty($items)){
echo '
<table style="border:2px solid #cc0000;width:400px">
<tr>
<td><strong>Item</strong></td>
<td><strong>Price</strong></td>
<td><strong>Quantity</strong></td>
<td><strong>Total</strong></td>
<td></td>
</tr>';
$total = 0;
foreach($items as $id=>$qty) {
foreach($products as $product) {
if($product['id'] == $id)
break;
}
if(!isset($product['name']))
continue;
echo '
<tr>
<td>' . $product['name'] . '</td>
<td>$' . $product['price'] . '</td>
<td>' . $qty . '</td>
<td>$' . ($product['price'] * $qty) . '</td>
<td><a href="?action=remove&id=' . $id . '">[x Remove]</a></td>
</tr>';
$total += $product['price'] * $qty;
}
echo '
<tr>
<td><a href="?action=empty">[Empty Cartt]</a></td>
<td colspan="4" align="right"><strong>Grand Total: $' . $total . '</strong></td>
</tr>
</table>';
}
else{
echo '<p style="color:#990000;">Your shopping cart is empty.</p>';
}
?>
</div>
我不知道是什么原因造成的。
任何解决方案将不胜感激!
最佳答案
看起来您正在渲染整个页面的副本。请注意重复的标题。
解决方案是确保index2.php(或任何最好的端点)仅包含信息模板,或者您有意重新渲染整个 View (并且应该设置父容器的html,而不是内层)。
关于javascript - JQuery GET 检索不需要的 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45121588/