我目前正在使用jQuery,Ajax和PHP实现购物车,并且大部分工作正在进行。然而,我目前卡在如何更新购物车页面内容时,我更新购物车,因为此刻我返回的HTML更新侧栏中的购物车区域(工作正常)。如何使用一个jquery ajax调用来更新页面上的多个区域?
所以我的问题是如何更新表格,同时在网站的主要内容区域显示所有的购物车项目?
我的jQuery(用于更新车):
$('.update_cart').submit(function (e) {
e.preventDefault();
$.ajax({
cache: false,
url: 'inc/shopping_bag.php',
data: $(this).serialize() + '&action=update',
type: 'POST',
success: function(html) {
$('#shopping-bag p').html(html);
}
});
});
我的PHP更新:
elseif (!empty($action) && $action == 'update') {
if (is_array($_POST['item_qty'])) {
foreach ($_POST['item_qty'] as $key=>$quantity) {
$quantity=ceil($quantity);
if ($quantity==0) {
unset($_SESSION['basket'][$key]);
} else {
$_SESSION['basket'][$key]['item_qty']=$quantity;
}
}
}
update_basket();
}
function update_basket() {
foreach ($_SESSION['basket'] as $array)
{
$totalItems+=$array['item_qty'];
$cost=$array['item_qty']*$array['unit_price'];
$total+=$cost;
}
echo 'Shopping Bag
'.$totalItems.' Items
£'.sprintf("%01.2f", $total);
}
我的购物车页面(对不起有点长):
Shopping Bag
<?php if (count($_SESSION['basket']) > 0) { ?>
QuantityItemUnit PriceTotal
$total=0;
$count=0;
foreach ($_SESSION['basket'] as $array)
{
$check_id = substr($array['item_id'], 0, 5);
$cost=sprintf("%01.2f", $array['item_qty']*$array['unit_price']);
$total+=$cost;
if (!empty($array['image'])) {
if (file_exists($array['image'])) {
$image_path = $array['image'];
} else {
$image_path = '';
}
} else {
$image_path = '';
}
$image = getImagesize($image_path);
$dimensions = imgResize($image[0], $image[1], 80);
if ($check_id=='parts') {
?>
alt="Diesel Injector Image" />
<?php echo $array['category']; ?> Injector
Part No: <?php echo $array['item_name']; ?>
£<?php echo str_replace("£ ","",$array['unit_price']); ?> £<?php echo $cost; ?> Remove Item} if ($check_id=='prods') { ?>
alt="Diesel Product Image" />
Product Code: <?php echo $array['item_name']; ?>
£<?php echo sprintf("%01.2f", $array['unit_price']); ?> £<?php echo $cost; ?> Remove Item$count++;
} ?>
You have no items in your shopping bag
任何帮助非常感谢,谢谢。
+0
你究竟想在桌上做什么?隐藏该行或将其标记为已添加?提供更多详情 –
2012-03-10 10:17:53
+0
对不起,你是对的我应该更具体。如果数量发生变化并点击“更新包”,或者如果项目被移除,则更新数据表中每个产品的数量和价格。我的问题是不这样做,但如何做到这一点,以及更新侧边栏中的购物车格。 –
2012-03-11 06:21:10
+1
使用JSON作为响应而不是HTML。所以你应该有这样的:'response = [{product:'a',price:1},{product:'b',price:2},...]',所以你可以重新使用它。 –
2012-03-11 08:59:18