将以下ASP购物车代码都保存为一个文件,如cart.asp,调用时比如加入购物车直接使用链接cart.asp?id=商品ID即可。本例中商品数据库表为product,使用到商品ID,商品名称product_name等,在实际使用ASP购物车代码时将相关参数替换下。 <%'简单ASP购物车代码原理 action=request.QueryString("action") if request.QueryString("id")="" then bookid=session("productlist")'//////////////////////////////////调入查询物品的id else if session("productlist")="" then session("productlist")=request.QueryString("id") bookid=request.QueryString("id") else if instr(request.querystring("id"),session("productlist"))<1 then bookid=session("productlist")+","+request.QueryString("id")'//////////////把id全部存储到bookid中类似与数组 session("productlist")=bookid else bookid=session("productlist") end if end if end if
if session("productlist")="" then'////////////////////////若id为空,则说明用户没有购物 bookid=0 end if
if action="del" then '删除购物车中的某一件商品 aProducts=split(Session("ProductList"),",") delid=cstr(trim(Request.QueryString("id"))) For i=0 To UBound(aProducts) '循环所有商品ID If trim(aProducts(i))<>delid then '不等于被删除的ID时则保存进新的列表中 sNewProducts = sNewProducts & "," & aProducts(i) end if Next Session("ProductList") = mid(sNewProducts,2) if session("ProductList")="" then bookid=0 else bookid=Session("ProductList") end if end if %>
以下是ASP购物车里的所有商品:<br><br> <%'根据临时存储到SESSION里的商品ID分别从商品数据库循环调出商品显示到购物车页面,遇到重复ID不显示 if bookid<>0 and bookid<>"" then set rs=server.CreateObject("adodb.recordset") dim sql sql="select id,product_name from product where id in ("&bookid&") order by id" '这里替换成实际的商品数据库及字段 rs.open sql,conn,1,1 dim bookscount,books '定义判断有几个bookid bookscount=request.QueryString("id").count aa=1 do while not rs.eof dim quatity '判断input 名 Quatity = CInt( Request( "ckxp"&rs("id")) ) If Quatity <=0 Then Quatity = 1 '以下为购物车每一件商品内容,包含ID、名称、数量及取消 %>
商品ID:<%=rs("id")%> 商品名称:<a href="showproduct.asp?id=<%=rs("id")%>" title="<%=rs("info")%>" target="_blank"><%=rs("product_name")%></a> 订购数量:<input name="sl<%=aa%>" type="text" Value="1" size="3"> 取消商品:<a href="?nav=m&id=<%=rs("id")%>&action=del"><font color="#FF0000" size="4" style="font-weight:bold">×</font></a> <br>
<%'循环读取ASP购物车内的商品 rs.movenext aa=aa+1 loop rs.close set rs=nothing %> <%if bookid=0 or bookid="" then%>ASP购物车内没有商品,请选择需订购的商品。<%end if%>
|