Ajax技术实现的购物车,使用Cookie保存。

首页 >> Ajax >> Ajax技术实现的购物车,使用Cookie保存。
Ajax技术实现的购物车,使用Cookie保存。
2008-5-9  作者:Army  关键字: AJAX实现的购物车,使用Cookie保存。,ajax,ajax实例,ajax教程
文章《 Ajax技术实现的购物车,使用Cookie保存。》来自ajax实例站
[ASPX]
<%@ Page Language="C#" MasterPageFile="~/Scripts/ShopCart/ShopCart.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" Title="购物车" %>
  
   <%@ Import Namespace="AW.Components.Helpers" %> 

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <asp:MultiView ID="MultiView1" runat="server">
        <asp:View ID="View1" runat="server">

            <script language="javascript" type="text/javascript" src='<%= this.ResolveUrl

("~/Utility/Functions.js") %>'></script>

            <script language="javascript" type="text/javascript">
        var key = '<%= Key %>';
        function remove(pID){
            var v = getCookie(key)==null?"":getCookie(key);
            _Default.RemoveProductFromOrder(pID,v,remove_Callback);
        }
        function remove_Callback(res){
            if(res.error!=null)alert(res.error);
            else{
               var tr = document.getElementById("tr_" + res.value.PID.toString());
               tr.style.display = "none";        
               deleteCookie(key,"/","." + location.host);
               setCookie(key,res.value.NVC,null,"/","."+location.host);
               calcMoney();
            }
        }
        function modify(pID,num){
            var v = getCookie(key)==null?"":getCookie(key);
            _Default.ModifyProductNumber(pID,num,v,modify_Callback);
        }
        function modify_Callback(res){
            deleteCookie(key,"/","." + location.host);
            setCookie(key,res.value.NVC,null,"/","."+location.host);   
            var total = document.getElementById("txtSubTotal_" + res.value.PID.toString());
            var price = document.getElementById("txtVipPrice_" + res.value.PID.toString());
            total.value = Round(parseFloat(parseInt(res.value.TOTAL) * parseFloat(price.value)),2);
            calcMoney();
        }
        function modifyAll(){
      
        }
        function clearCart(){
            if (!confirm('确定要清空购物车吗?')) return;
            var tb = document.getElementById("tbOrder");
               for(var i=1;i<tb.rows.length;i++){
                    var tr = tb.rows.item(i);
                    if(tr.id.indexOf("_")!=-1 && tr.style.display!="none"){
                        tr.style.display = 'none';
                     }
                } 
             deleteCookie(key,"/","." + location.host);
            var ctlTotalNum = document.getElementById("<%=lbTotalNum.ClientID %>");
            var ctlTotalMoney = document.getElementById("<%=lbTotalMoney.ClientID %>");
            var ctlDiscount = document.getElementById("<%=lbDiscount.ClientID %>");    
            ctlTotalNum.innerHTML = "0";           
            ctlTotalMoney.innerHTML = "0";
            ctlDiscount.innerHTML = "0";
        }
       
        function calcMoney(){
            var ctlNums = document.getElementsByName("txtNumber");
            var ctlPrices = document.getElementsByName("txtPrice");
            var ctlVipPrices = document.getElementsByName("txtVipPrice");
            var ctlSubTotal = document.getElementsByName("txtSubTotal");
            var ctlTotalNum = document.getElementById("<%=lbTotalNum.ClientID %>");
            var ctlTotalMoney = document.getElementById("<%=lbTotalMoney.ClientID %>");
            var ctlDiscount = document.getElementById("<%=lbDiscount.ClientID %>");    
            var totalNum = 0;
            var subTotal = 0;
            var subTotalVip = 0;
            var totalMoney = 0; 
            var totalVipMoney = 0;
           
            for(var i=0;i<ctlNums.length;i++){
                totalNum += parseInt(ctlNums[i].value);
                subTotal  = parseFloat(totalNum * parseFloat(ctlPrices[i].value));
                subTotalVip =  parseFloat(totalNum * parseFloat(ctlVipPrices[i].value));
                totalMoney +=  subTotal;
                totalVipMoney += subTotalVip;
               ctlSubTotal.value = subTotalVip.toString();
            }
            ctlTotalNum.innerHTML = Round(totalNum,2);
            ctlTotalMoney.innerHTML = Round(totalVipMoney,2);
            ctlDiscount.innerHTML = Round((totalMoney - totalVipMoney),2);
        }
        function Round(a_Num , a_Bit){
            return (Math.round(a_Num * Math.pow (10 , a_Bit)) / Math.pow(10 , a_Bit)).toString()  ;
        }
        </script>

            <div id="shopcart">
                <table width="778" border="0" align="center" cellpadding="0" cellspacing="0"

background="../../Icon/ShopCart/shopC_syp_5.gif">
                    <tbody>
                        <tr>
                            <td width="12">
                                <img height="72" src="../../Icon/ShopCart/shopC_syp_1.gif" width="12"

/></td>
                            <td>
                                <img height="72" src="../../Icon/ShopCart/shopC_6.gif" width="176"

/></td>
                            <td valign="bottom" align="right">
                                <img height="29" src="../../Icon/ShopCart/shopC_4.gif" width="324"

/></td>
                            <td width="10" align="right" valign="bottom">
                                <img height="72" src="../../Icon/ShopCart/shopC_syp_3.gif" width="10"

/></td>
                        </tr>
                    </tbody>
                </table>
                <table class="meun_bg" cellspacing="0" cellpadding="0" width="540" align="center"
                    border="0">
                    <tbody>
                        <tr>
                            <td align="right">
                                <img height="28" src="../../Icon/ShopCart/shopC_syx_01.gif" width="93"

border="0" /></td>
                            <td>
                                <img height="32" src="../../Icon/ShopCart/shopC_sy_8.gif" width="55"

/></td>
                            <td>
                                <img height="28" src="../../Icon/ShopCart/shopC_syx_02.gif" width="112"

border="0" /></td>
                            <td>
                                <img height="32" src="../../Icon/ShopCart/shopC_sy_8.gif" width="55"

/></td>
                            <td>
                                <img height="22" src="../../Icon/ShopCart/shopC_syx_03.gif" width="109"

border="0" /></td>
                        </tr>
                    </tbody>
                </table>
                <table cellspacing="0" cellpadding="0" width="778" align="center" bgcolor="#fafafa"
                    border="0">
                    <tbody>
                        <tr>
                            <td>
                                <img height="41" hspace="8" src="../../Icon/ShopCart/shopc_z1.gif"

width="143" /></td>
                        </tr>
                        <tr>
                            <td>
                                <table cellspacing="0" cellpadding="0" width="96%" align="center"

border="0">
                                    <tbody>
                                        <tr align="right" bgcolor="#fafafa">
                                            <td>
                                                <img height="15"

src="../../Icon/ShopCart/shopc_syx_j.gif" width="771" /></td>
                                        </tr>
                                        <tr align="right" bgcolor="#fafafa">
                                            <td class="boder_center_bg">
                                                <table cellspacing="1" width="95%" align="center"

border="0" id="tbOrder">
                                                    <tbody>
                                                        <tr class="boder_topbg" align="center">
                                                            <td>
                                                                商品名称</td>
                                                            <td>
                                                                单 位</td>
                                                            <td>
                                                                数 量</td>
                                                            <td>
                                                                市场价(元)</td>
                                                            <td>
                                                                会员价(元)</td>
                                                            <td>
                                                                小 计(元)</td>
                                                            <td width="8%">
                                                                操作</td>
                                                        </tr>
                                                        <asp:Repeater ID="rptView" runat="server">
                                                            <ItemTemplate>
                                                                <tr align="center" bgcolor="#f9f9f9"

id="tr_<%# ((ORDERDETAIL)Container.DataItem).Product.ID %>">
                                                                    <td align="left">
                                                                        <asp:HyperLink Target="_blank"

NavigateUrl='<%# "~/" + ((ORDERDETAIL)Container.DataItem).Product.ChannelID.ToString() + "_" +

((ORDERDETAIL)Container.DataItem).Product.ID.ToString() + ".aspx" %>'
                                                                            Text='<%# ((ORDERDETAIL)

Container.DataItem).Product.Name %>' runat="server" /></td>
                                                                    <td>
                                                                        <%# String.IsNullOrEmpty

(((ORDERDETAIL)Container.DataItem).Product.Unit) ? "个" : ((ORDERDETAIL)

Container.DataItem).Product.Unit %>
                                                                    </td>
                                                                    <td>
                                                                        <input style="text-align:

right;" onbeforepaste="clipboarddata.setdata('text',clipboarddata.getdata('text').replace(/

[^/d]/g,''))"
                                                                            id="txtNum_<%#

((ORDERDETAIL)Container.DataItem).Product.ID %>" οnkeyup="value=value.replace(/[^/d]/g,'');"
                                                                            οnblur="if

(this.value.length==0)this.value=0;modify(<%# ((ORDERDETAIL)Container.DataItem).Product.ID %>,value);"
                                                                            maxlength="2" size="4"

value="<%# ((ORDERDETAIL)Container.DataItem).Number %>"
                                                                            name="txtNumber" /></td>
                                                                    <td style="padding-left: 20px"

align="right">
                                                                        <del>
                                                                            <%# ((ORDERDETAIL)

Container.DataItem).Product.Price %>
                                                                        </del>
                                                                        <input name='txtPrice'

id="txtPrice_<%# ((ORDERDETAIL)Container.DataItem).Product.ID %>"
                                                                            type="hidden" value='<%#

((ORDERDETAIL)Container.DataItem).Product.Price %>' />
                                                                    </td>
                                                                    <td style="padding-left: 20px"

align="right">
                                                                        <input style="text-align:

right;" name='txtVipPrice' id="txtVipPrice_<%# ((ORDERDETAIL)Container.DataItem).Product.ID %>"
                                                                            type="hidden" value='<%#

((ORDERDETAIL)Container.DataItem).Product.VipPrice %>' />
                                                                        <%# ((ORDERDETAIL)

Container.DataItem).Product.VipPrice %>
                                                                    </td>
                                                                    <td style="padding-left: 20px"

align="right">
                                                                        <input style="text-align:

right;border: none 0px white; background-color: White;" size="4" name='txtSubTotal' id="txtSubTotal_<%#

((ORDERDETAIL)Container.DataItem).Product.ID %>"
                                                                            type="text"

readonly="readonly" value='<%# ((ORDERDETAIL)Container.DataItem).Product.VipPrice * ((ORDERDETAIL)

Container.DataItem).Number %>' /></td>
                                                                    <td>
                                                                        <a href="javascript:remove(<%#

((ORDERDETAIL)Container.DataItem).Product.ID %>);"><font
                                                                            color="#ff0000">删除

</font></a></td>
                                                                </tr>
                                                            </ItemTemplate>
                                                        </asp:Repeater>
                                                        <tr align="right" bgcolor="#f9f9f9">
                                                            <td colspan="7">
                                                                购物车中共有
                                                                <asp:Label ID="lbTotalNum"

ForeColor="red" runat="server" />
                                                                件商品,共计 <font

class="font_red">¥<asp:Label ID="lbTotalMoney" runat="server" />
                                                                    元</font>(不包括邮费) &nbsp;您节

省了<font class="font_red">¥<asp:Label ID="lbDiscount" runat="server" /></font>
                                                            </td>
                                                        </tr>
                                                        <tr align="left" bgcolor="#f9f9f9">
                                                            <td colspan="7">
                                                                <img style="width: 104px; height: 27px;

cursor: pointer;" οnclick="modifyAll();"
                                                                    height="23" alt="单击这里保存您所修

改的商品数量" width="85" src="../../Icon/ShopCart/shopc_13_02.gif"
                                                                    border="0" />
                                                                &nbsp;
                                                                <img style="cursor: pointer"

οnclick="clearCart();" height="27" alt="单击这里清空所有购买的商品"
                                                                   

src="../../Icon/ShopCart/shopc_13_03.gif" width="104" />&nbsp;</td>
                                                        </tr>
                                                    </tbody>
                                                </table>
                                            </td>
                                        </tr>
                                        <tr align="right" bgcolor="#fafafa">
                                            <td>
                                                <img height="15" src="../../Icon/ShopCart/shopc_20.gif"

width="771" /></td>
                                        </tr>
                                    </tbody>
                                </table>
                            </td>
                        </tr>
                        <tr>
                            <td align="right">
                                <img style="cursor: hand" οnclick="javascript:window.close();"

height="42" alt="点击继续购买您喜欢的其它商品"
                                    src="../../Icon/ShopCart/shopc_13_01.gif" width="143" vspace="10"

/>&nbsp; &nbsp;
                                &nbsp;
                                <img style="cursor: hand" οnclick="location.href='./ClientInfo.aspx';"

height="42"
                                    alt="点击去收银台结帐" hspace="10"

src="../../Icon/ShopCart/shopc_13.gif" width="143"
                                    vspace="10" id="IMG1" /></td>
                        </tr>
                        <tr>
                            <td class="style2" align="center">
                            </td>
                        </tr>
                    </tbody>
                    <tr>
                        <td>
                        </td>
                    </tr>
                </table>
            </div>
        </asp:View>
    </asp:MultiView>
    <br />
    <br />
</asp:Content>

[CS]
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using AW.Components;
using AjaxPro;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;

using AW.Components.Helpers;

public partial class _Default : System.Web.UI.Page {
    protected string Key = "ORDERDETAIL_" + CContext.Current.SiteOwnerUserID.ToString();
    protected void Page_Load(object sender, EventArgs e) {
        Utility.RegisterTypeForAjax(typeof(_Default));

        string action = Request["Act"];
        int id;

        if (string.IsNullOrEmpty(action))
            action = "list";

        if (int.TryParse(Request["ID"], out id)) {
            if (action == "add") {
                CProduct prodcut = CProducts.GetProduct(id, CContext.Current.SiteOwnerUserID);
                if (prodcut == null) {
                    CJS.AlertAndGoUrl("此商品已经被删除!", Request.Url.AbsolutePath);
                    return;
                }
                AddProductToOrder(id, 1);
                Response.Redirect(Request.Url.AbsolutePath, true);
                return;
            }
        }
        rptView.DataSource = GetOrders();
        rptView.DataBind();

        MultiView1.ActiveViewIndex = 0;
    }

    public List<ORDERDETAIL> GetOrders() {
        HttpCookie cookie;
        cookie = Request.Cookies[Key] == null ? new HttpCookie(Key) : Request.Cookies[Key];
        NameValueCollection nvc = CHttpHelper.Base64Decode(cookie.Value);
        List<ORDERDETAIL> orders = new List<ORDERDETAIL>();
        int totalNum = 0;
        double totalMoney = 0.00;
        double totalVipMoney = 0.00;
        for (int i = 0; i < nvc.Count; i++) {
            ORDERDETAIL ord = new ORDERDETAIL(int.Parse(nvc.Keys[i]), int.Parse(nvc[i]));
            orders.Add(ord);
            totalNum += int.Parse(nvc[i]);
            totalMoney += (ord.Number * (ord.Product==null?0:ord.Product.Price));
            totalVipMoney += (ord.Number * (ord.Product==null?0:ord.Product.VipPrice));
        }
        lbTotalNum.Text = totalNum.ToString();
        lbTotalMoney.Text = totalVipMoney.ToString("0.00");
        lbDiscount.Text = (totalMoney - totalVipMoney).ToString("0.00");
        return orders;
    }

    public void AddProductToOrder(int pID, int num) {
        HttpCookie cookie;
        cookie = Request.Cookies[Key] == null ? new HttpCookie(Key) : Request.Cookies[Key];
        cookie.Path = Request.ApplicationPath;
        cookie.Domain = "." + Request.Url.Host;
        NameValueCollection nvc = CHttpHelper.Base64Decode(cookie.Value);
        if (nvc[pID.ToString()] != null)
            nvc[pID.ToString()] = (int.Parse(nvc[pID.ToString()]) + num).ToString();
        else
            nvc.Add(pID.ToString(), num.ToString());

        cookie.Value = CHttpHelper.Base64Encode(nvc);
        Response.AppendCookie(cookie);
    }

    [AjaxMethod]
    public RESUTLINFO ModifyProductNumber(int pID, int num, string cookieStr) {
        NameValueCollection nvc = CHttpHelper.Base64Decode(cookieStr);
        nvc[pID.ToString()] = num.ToString();
        return new RESUTLINFO(pID, int.Parse(nvc[pID.ToString()]),CHttpHelper.Base64Encode(nvc));
    }

    [AjaxMethod]
    public RESUTLINFO RemoveProductFromOrder(int pID, string cookieStr) {
        NameValueCollection nvc = CHttpHelper.Base64Decode(cookieStr);
        nvc.Remove(pID.ToString());
        return new RESUTLINFO(pID, CHttpHelper.Base64Encode(nvc));
    }
}

[CHttpHeler]
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Specialized;
using System.Web;

namespace AW.Components.Helpers {
    public class CHttpHelper {
        private CHttpHelper() { }

        GetString#region GetString
        public static string GetString(NameValueCollection nvc) {
            string rtn = string.Empty;
            for (int i = 0; i < nvc.Count; i++) {
                rtn += nvc.Keys[i] + "=" + nvc[i];
                if (i < nvc.Count - 1) rtn += "&";
            }
            return rtn;
        }

        public static string GetString(string base64String) {
            byte[] bytes = Convert.FromBase64String(base64String);
            return Encoding.Default.GetString(bytes);
        }
        #endregion

        public static string Base64Encode(NameValueCollection nvc) {
            return Convert.ToBase64String(Encoding.Default.GetBytes(GetString(nvc)),

Base64FormattingOptions.None);
        }

        public static NameValueCollection Base64Decode(string base64String) {
            if (string.IsNullOrEmpty(base64String))
                return new NameValueCollection();

            return HttpUtility.ParseQueryString(GetString(HttpUtility.UrlDecode(base64String)));
        }
    }

    public struct ORDERDETAIL {
        public ORDERDETAIL(int pID, int num) {
            Product = CProducts.GetProduct(pID, CContext.Current.SiteOwnerUserID);
            Number = num;
        }

        public CProduct Product;
        public int Number;

        public void ParseFromString(string str) {

        }

        public int ProudctID {
            get {
                return Product == null ? 0 : Product.ID;
            }
        }

        public override string ToString() {
            return ProudctID + ":" + Number.ToString();
        }
    }

    public struct RESUTLINFO {
        public string NVC;
        public int PID;
        public int TOTAL;

        public RESUTLINFO(int pID, string nvc) {
            PID = pID;
            NVC = nvc;
            TOTAL = 0;
        }

        public RESUTLINFO(int pID, int total, string nvc) {
            PID = pID;
            NVC = nvc;
            TOTAL = total;
        }
    }
}


版权所有© 2008-2009 AJAX实例站

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package shoppingcart.biz; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * 购物车 */ public class ShoppingCart { private Map cartMap = null; //保存Product的Map /** * 购物车构造函数 */ public ShoppingCart(){ cartMap = new HashMap(); } /** * 取得存放产品的cartMap */ public Map getCartMap(){ return this.cartMap; } /** * 向购物车添加产品 */ public boolean addProduct(String productId){ if(existProduct(productId)){ // 产品已存在则增加数量 Product product = cartMap.get(productId); product.setProductNum(product.getProductNum() + 1); return true; } else{ // 否则新加入该产品 Product product = new Product(productId); if(product.getProductId()==null){ return false; // 数据库中无该产品 }else{ cartMap.put(productId, product); return false; } } } /** * 检查购物车里是否已存在该产品 */ public boolean existProduct(String productId){ Iterator hmkey = cartMap.keySet().iterator(); while(hmkey.hasNext()){ String pid = hmkey.next(); if(pid.equals(productId)){ return true; } } return false; } /** * 从购物车中移除指定产品 */ public void delProduct(String productId){ cartMap.remove(productId); } /** * 获取购物车产品数量 */ public int getProductNum(){ int productNum = 0; Iterator hmEntry = cartMap.values().iterator(); while(hmEntry.hasNext()){ productNum += hmEntry.next().getProductNum(); } return productNum; } /** * 统计购物车商品总价 */ public double getTotalprice(){ double totalPrice = 0.0; Iterator hmkey = cartMap.keySet().iterator(); Product product = null; while(hmkey.hasNext()){ product = cartMap.get(hmkey.next()); totalPrice += product.getProductPirce() * product.getProductNum(); } return totalPrice; } /** * 清空购物车 */ public void clearCart(){ cartMap.clear(); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值