ecshop购物车页面使用ajax更新商品数量、小计、总价,点击加号和减号

第一步

我先把 我的购物车页面flow.dwt的商品列表部分的代码贴出来,这样比较起来方便一点

<div class="flowBox">
    <h6><span>{$lang.goods_list}</span></h6>
    
      <div class="flowBox_in">
        <form id="formCart" name="formCart" method="post" action="flow.php">
           <table width="99%" align="center" border="0" cellpadding="5" cellspacing="1" bgcolor="#aacded">
            <tr>
              <th bgcolor="#ebf4fb">{$lang.goods_name}</th>

              <!-- {if $show_marketprice} 显示市场价 -->
              <th bgcolor="#ebf4fb">{$lang.market_prices}</th>
              <!-- {/if} -->
              <th bgcolor="#ebf4fb">{$lang.shop_prices}</th>
              <th bgcolor="#ebf4fb">{$lang.number}</th>
              <th bgcolor="#ebf4fb">{$lang.subtotal}</th>
              <th bgcolor="#ebf4fb">{$lang.handle}</th>
            </tr>
            <!-- {foreach from=$goods_list item=goods} -->
            <tr  id="tr_goods_{$goods.rec_id}">
              <td bgcolor="#ffffff" align="center">
                <!-- {if $goods.goods_id gt 0 && $goods.extension_code neq 'package_buy'} 商品 -->
                  <!-- {if $show_goods_thumb eq 1} -->
                    <a href="goods.php?id={$goods.goods_id}" target="_blank" class="f6">{$goods.goods_name}</a>
                  <!-- {elseif $show_goods_thumb eq 2} -->
                    <a href="goods.php?id={$goods.goods_id}" target="_blank"><img style="width:50px" src="{$goods.goods_thumb}" border="0" title="{$goods.goods_name|escape:html}" /></a>
                  <!-- {else} -->
                    <a href="goods.php?id={$goods.goods_id}" target="_blank"><img style="width:50px"  src="{$goods.goods_thumb}" border="0" title="{$goods.goods_name|escape:html}" /></a><br />
                    <a href="goods.php?id={$goods.goods_id}" target="_blank" class="f6">{$goods.goods_name}</a>
                  <!-- {/if} -->
                  <!-- {if $goods.parent_id gt 0} 配件 -->
                  <span style="color:#FF0000">({$lang.accessories})</span>
                  <!-- {/if} -->
                  <!-- {if $goods.is_gift gt 0} 赠品 -->
                  <span style="color:#FF0000">({$lang.largess})</span>
                  <!-- {/if} -->
                <!-- {elseif $goods.goods_id gt 0 && $goods.extension_code eq 'package_buy'} -->
                  <a href="javascript:void(0)" οnclick="setSuitShow({$goods.goods_id})" class="f6">{$goods.goods_name}<span style="color:#FF0000;">({$lang.remark_package})</span></a>
                  <div id="suit_{$goods.goods_id}" style="display:none">
                      <!-- {foreach from=$goods.package_goods_list item=package_goods_list} -->
                        <a href="goods.php?id={$package_goods_list.goods_id}" target="_blank" class="f6">{$package_goods_list.goods_name}</a><br />
                      <!-- {/foreach} -->
                  </div>
                <!-- {else} 优惠活动 -->
                  {$goods.goods_name}
                <!-- {/if} -->
              </td>

              <!-- {if $show_marketprice} 显示市场价 -->
              <td align="center" bgcolor="#ffffff">{$goods.market_price}</td>
              <!-- {/if} -->
              <td align="center" bgcolor="#ffffff">{$goods.goods_price}</td>
              <td align="center" bgcolor="#ffffff">
                <!-- {if $goods.goods_id gt 0 && $goods.is_gift eq 0 && $goods.parent_id eq 0} 普通商品可修改数量 -->
                <a οnclick="changenum({$goods.rec_id},-1)" style="height:12px; color:#000; line-height:12px; padding:0px 4px; background:#fff; border:1px #eee solid; display:inline-block;" href="javascript:void(0)" >-</a>
                <input type="text" name="goods_number[{$goods.rec_id}]" id="goods_number_{$goods.rec_id}" value="{$goods.goods_number}" size="3"class="inputBg" style="text-align:center " οnchange="change_goods_number({$goods.rec_id},this.value)"/>
                <a οnclick="changenum({$goods.rec_id},1)"  style="height:12px; color:#000; line-height:12px; padding:0px 4px; background:#fff; border:1px #eee solid; display:inline-block;" href="javascript:void(0)" >+</a>
                <!-- {else} -->
                {$goods.goods_number}
                <!-- {/if} -->
              </td>

              <td align="center" bgcolor="#ffffff" id="goods_subtotal_{$goods.rec_id}">
          <span>{$goods.subtotal}</span>
          </td>

              <td align="center" bgcolor="#ffffff">
                <a href="javascript:if (confirm('{$lang.drop_goods_confirm}')) location.href='flow.php?step=drop_goods&id={$goods.rec_id}'; " class="f6">{$lang.drop}</a>
                <!-- {if $smarty.session.user_id gt 0 && $goods.extension_code neq 'package_buy'} 如果登录了,可以加入收藏 -->
                <a href="javascript:if (confirm('{$lang.drop_goods_confirm}')) location.href='flow.php?step=drop_to_collect&id={$goods.rec_id}'; " class="f6">{$lang.drop_to_collect}</a>
                <!-- {/if} -->            
                </td>
            </tr>
            <!-- {/foreach} -->
          </table>
          <table width="99%" align="center" border="0" cellpadding="5" cellspacing="1" bgcolor="#aacded">
            <tr>
              <td bgcolor="#ebf4fb" id="total_desc">
              <!-- {if $discount gt 0} -->{$your_discount}<br /><!-- {/if} -->
              {$shopping_money}<!-- {if $show_marketprice} -->,{$market_price_desc}<!-- {/if} -->
              </td>
              <td align="right" bgcolor="#ebf4fb">
                <input type="button" value="{$lang.clear_cart}" class="bnt_blue_1" οnclick="location.href='flow.php?step=clear'" />
                
              </td>
            </tr>
          </table>

第二步

我把js函数写出来

<script type="text/javascript">
            function changenum(rec_id, diff)
            {
                var goods_number =Number($$('goods_number_' + rec_id).value) + Number(diff);             
                change_goods_number(rec_id,goods_number);
            }
            function change_goods_number(rec_id, goods_number)
            {   
               if(goods_number >= 1){
                  Ajax.call('flow.php?step=ajax_update_cart', 'rec_id=' + rec_id +'&goods_number=' + goods_number, change_goods_number_response, 'POST','JSON');
               }                              
            }
            function change_goods_number_response(result)
            {               
                if (result.error == 0)
                {
                    var rec_id = result.rec_id;
                    var tr_goods = 'tr_goods_' + rec_id;
                    
                    $$('goods_number_' +rec_id).value = result.goods_number;//更新数量
                    $$('goods_subtotal_' +rec_id).innerHTML = result.goods_subtotal;//更新小计
                    if (result.goods_number <= 0)
                    {// 数量为零则隐藏所在行
                        $$(tr_goods).style.display = 'none';
                        $$(tr_goods).innerHTML = '';
                    }
                    $$('total_desc').innerHTML =result.total_desc;//更新合计
                    if ($$('ECS_CARTINFO'))
                    {//更新购物车数量
                       $$('ECS_CARTINFO').innerHTML = result.cart_info;
                    }
                }
                else if (result.message != '')
                {
                    alert(result.message);
                }                
            }
        </script>

以上两部分是flow.dwt页面全部的代码

第三步

也就是要处理ajax请求的php代码,是flow.php文件

//-- 更新购物车商品数量

/*------------------------------------------------------ */

elseif ($_REQUEST['step']== 'ajax_update_cart')
{
    require_once(ROOT_PATH .'includes/cls_json.php');
    $json = new JSON();
    $result = array('error' => 0, 'message'=> '');
    if (isset($_POST['rec_id']) && isset($_POST['goods_number']))
    {
        $key = $_POST['rec_id'];
        $val = $_POST['goods_number'];
        $val = intval(make_semiangle($val));
        if ($val <= 0 && !is_numeric($key))
        {
            $result['error'] = 99;
            $result['message'] = '';
            die($json->encode($result));
        }
        
        //查询:
        $sql = "SELECT `goods_id`, `goods_attr_id`,`product_id`, `extension_code` FROM" .$GLOBALS['ecs']->table('cart').
            " WHERE rec_id='$key' AND session_id='" . SESS_ID . "'";
        $goods =$GLOBALS['db']->getRow($sql);
        
        $sql = "SELECT g.goods_name,g.goods_number ".
             "FROM ".$GLOBALS['ecs']->table('goods'). " AS g, ".
                 $GLOBALS['ecs']->table('cart'). " AS c ".
                "WHERE g.goods_id =c.goods_id AND c.rec_id = '$key'";
            $row = $GLOBALS['db']->getRow($sql);
        
        
        //查询:系统启用了库存,检查输入的商品数量是否有效
        if(intval($GLOBALS['_CFG']['use_storage']) > 0 && $goods['extension_code'] != 'package_buy')
        {
            if ($row['goods_number'] < $val)
            {
                $result['error'] = 1;
                $result['message'] =sprintf($GLOBALS['_LANG']['stock_insufficiency'], $row['goods_name'],$row['goods_number'], $row['goods_number']);
                die($json->encode($result));
            }
            /* 是货品*/
            $goods['product_id'] = trim($goods['product_id']);
            if (!empty($goods['product_id']))
            {
                $sql = "SELECT product_number FROM " .$GLOBALS['ecs']->table('products'). " WHERE goods_id = '" . $goods['goods_id'] . "' AND product_id = '" .$goods['product_id'] . "'";
                
                $product_number =$GLOBALS['db']->getOne($sql);
                if ($product_number < $val)
                {
                    $result['error'] = 2;
                    $result['message'] =sprintf($GLOBALS['_LANG']['stock_insufficiency'], $row['goods_name'],
                    $product_number['product_number'], $product_number['product_number']);
                    die($json->encode($result));
                    }
            }
        }
        elseif (intval($GLOBALS['_CFG']['use_storage'])> 0 && $goods['extension_code'] == 'package_buy')
        {
            if(judge_package_stock($goods['goods_id'], $val))
            {
                $result['error'] = 3;
                $result['message'] =$GLOBALS['_LANG']['package_stock_insufficiency'];
                die($json->encode($result));
                }
            }
            
        /* 查询:检查该项是否为基本件 以及是否存在配件*/
        /* 此处配件是指添加商品时附加的并且是设置了优惠价格的配件 此类配件都有parent_idgoods_number为1 */
        $sql = "SELECT b.goods_number,b.rec_id FROM ".$GLOBALS['ecs']->table('cart') . " a, ".$GLOBALS['ecs']->table('cart') . " b WHERE a.rec_id = '$key' AND a.session_id = '" .SESS_ID . "' AND a.extension_code <> 'package_buy' AND b.parent_id = a.goods_id AND b.session_id = '" .SESS_ID . "'";
        
        
        $offers_accessories_res =$GLOBALS['db']->query($sql);
        //订货数量大于0
        if ($val > 0)
        {
            /* 判断是否为超出数量的优惠价格的配件 删除*/
            $row_num = 1;
            while ($offers_accessories_row =$GLOBALS['db']->fetchRow($offers_accessories_res))
            {
                if ($row_num > $val)
                {
                    $sql = "DELETE FROM" . $GLOBALS['ecs']->table('cart') .
                        " WHERE session_id = '" . SESS_ID . "' " .
                        "AND rec_id ='" . $offers_accessories_row['rec_id'] ."' LIMIT 1";
                        $GLOBALS['db']->query($sql);
                }
                
                $row_num ++;
            }
            
            /* 处理超值礼包*/
            if ($goods['extension_code'] =='package_buy')
            {
                //更新购物车中的商品数量
                $sql = "UPDATE ".$GLOBALS['ecs']->table('cart').
                        " SET goods_number= '$val' WHERE rec_id='$key' AND session_id='" . SESS_ID . "'";
            }
            /* 处理普通商品或非优惠的配件*/
            else
            {
                $attr_id    = empty($goods['goods_attr_id']) ? array(): explode(',', $goods['goods_attr_id']);
                $goods_price =get_final_price($goods['goods_id'], $val, true, $attr_id);
                
                //更新购物车中的商品数量
                $sql = "UPDATE ".$GLOBALS['ecs']->table('cart').
                        " SET goods_number= '$val', goods_price = '$goods_price' WHERE rec_id='$key' AND session_id='" . SESS_ID . "'";
            }
        }
        //订货数量等于0
        else
        {
            /* 如果是基本件并且有优惠价格的配件则删除优惠价格的配件*/
            while ($offers_accessories_row =$GLOBALS['db']->fetchRow($offers_accessories_res))
            {
                $sql = "DELETE FROM ". $GLOBALS['ecs']->table('cart') .
                        " WHERE session_id= '" . SESS_ID . "' " .
                        "AND rec_id ='" . $offers_accessories_row['rec_id'] ."' LIMIT 1";
                        $GLOBALS['db']->query($sql);
            }
            
            $sql = "DELETE FROM ".$GLOBALS['ecs']->table('cart').
                " WHERE rec_id='$key' AND session_id='" .SESS_ID. "'";
        }
        
        $GLOBALS['db']->query($sql);
        
        /* 删除所有赠品*/
        $sql = "DELETE FROM " .$GLOBALS['ecs']->table('cart') . " WHERE session_id = '" .SESS_ID."' AND is_gift <> 0";
        $GLOBALS['db']->query($sql);
        
        $result['rec_id'] = $key;
        $result['goods_number'] = $val;
        $result['goods_subtotal'] = '';
        $result['total_desc'] = '';
        $result['cart_info'] =insert_cart_info();
        /* 计算合计*/
        $cart_goods = get_cart_goods();
        foreach ($cart_goods['goods_list'] as $goods )
        {
            if ($goods['rec_id'] == $key)
            {
                $result['goods_subtotal'] =$goods['subtotal'];
                break;
            }
        }
        $shopping_money = sprintf($_LANG['shopping_money'], $cart_goods['total']['goods_price']);
        $market_price_desc = sprintf($_LANG['than_market_price'],$cart_goods['total']['market_price'],$cart_goods['total']['saving'], $cart_goods['total']['save_rate']);
        
        /* 计算折扣*/
        $discount = compute_discount();
        $favour_name = empty($discount['name'])? '' : join(',', $discount['name']);
        $your_discount =sprintf($_LANG['your_discount'], $favour_name,price_format($discount['discount']));
        
        if ($discount['discount'] > 0)
        {
            $result['total_desc'] .=$your_discount . '<br />';
        }
        $result['total_desc'] .=$shopping_money;
        if ($_CFG['show_marketprice'])
        {
            $result['total_desc'] .= ',' .$market_price_desc;
        }
        die($json->encode($result));
    }
    else
    {
        $result['error'] = 100;
        $result['message'] = '';
        die($json->encode($result));
    }
}


  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值