購物車添加
購物車頁面
需要用戶id,商品id,商家id,規(guī)格id,規(guī)格信息,規(guī)格價格,庫存數(shù)量,購買數(shù)量,購買時間
購物車表
DROP TABLE IF EXISTS spcar;
CREATE TABLE spcar(
carId VARCHAR(32) PRIMARY KEY COMMENT'主鍵',
uid VARCHAR(32) NOT NULL COMMENT'用戶id',
pdId VARCHAR(32) NOT NULL COMMENT'商品id',
comId VARCHAR(32) NOT NULL COMMENT'商家id',
ggId VARCHAR(32) NOT NULL COMMENT'規(guī)格id',
pcInfo VARCHAR(255) NOT NULL COMMENT'規(guī)格信息',
pcprice DECIMAL(9,2) NOT NULL COMMENT'規(guī)格價格',
pcCount INT NOT NULL COMMENT'庫存數(shù)量',
spCount INT NOT NULL COMMENT'購買數(shù)量',
joinTime DATETIME NOT NULL COMMENT'購買時間',
y1 VARCHAR(255) COMMENT '預(yù)留1',
y2 VARCHAR(255) COMMENT '預(yù)留2',
y3 VARCHAR(255) COMMENT '預(yù)留3'
);
ALTER TABLE spcar ADD CONSTRAINT fk_users_spcar FOREIGN KEY (uid) REFERENCES users(userid);
ALTER TABLE spcar ADD CONSTRAINT fk_product_spcar FOREIGN KEY (pdId) REFERENCES product(pid);
ALTER TABLE spcar ADD CONSTRAINT fk_com_spcar FOREIGN KEY (comId) REFERENCES users(userid);
ALTER TABLE spcar ADD CONSTRAINT fk_prodCount_spcar FOREIGN KEY (ggId) REFERENCES prodCount(pcid);
添加購物車
<a id="LikBasket" title="加入購物車" href="javascript:f2()"><i></i>加入購物車</a>
思路:
- 用戶id:可以從session中獲取
- 規(guī)格信息:選中的規(guī)格用#拼接起來
- 商品id:
${param.id}
- 商家id:在service層根據(jù)商品id查出商家id
- 規(guī)格id:在service層根據(jù)商品id和規(guī)格信息
11#22
查到規(guī)格id
1. 頁面上參數(shù)的獲取和處理
- 規(guī)格的id是選中的規(guī)格標簽的xxyyzz的值用#拼接
- 一級規(guī)格都要選上才能添加到購物車,可以定義一個全局變量
var spgejhsl=0;
- 在顯示詳情頁面的時候
spgejhsl = dt.data.yjge.length;
保存規(guī)格數(shù) - 用來判斷規(guī)格是否全選上,數(shù)量也不能為零
- 從session中獲得
userId
必須登陸才可以加入購物車
function f2(){
//獲取選擇的規(guī)格
var allg = $(".theme-options ul .selected");
var gids = "";
$.each(allg,function(i,n){
gids+=$(n).attr("xxyyzz");
if( i < allg.length-1)gids+="#";
});
//單價
var price=$(".sys_item_price").html();
//購買數(shù)量
var ct = $("#text_box").val();
var us = "${lged.userId}";
//是否登錄?
if( !us || us.length == 0 ){
//("#xyz").dialog()
alert("請先登錄");
}
//只顯示 二級規(guī)格 的 上級規(guī)格 集合
//購買數(shù)量 > 0 驱还, 規(guī)格都要選 才可 提交
if( allg.length != spgejhsl || ct=='0' ) return; //JM抖印6吡稀!比較
$.ajax({
url: "ctrl/users/joinCar.do",
type: "post",
data:{
"uid":'${lged.userId}',
"pdid":'${param.id}',
"gginfo":gids,
"buyCount":ct,
"price":price
}
})
}//f2
2. Controller
- 用Map集合來封裝購物車的屬性,其他屬性交給service層
- 向JSON中存入是否添加成功的信息,返回給頁面
@RequestMapping("/joinCar")
@ResponseBody
public void carAdd(@RequestParam String uid,@RequestParam String pdid,
@RequestParam String gginfo,@RequestParam String buyCount,
@RequestParam double price,HttpServletResponse resp) throws IOException{
System.out.println("日志1...接:" + uid +"\t 商品:"+pdid+"\t規(guī)格:" + gginfo+"\t數(shù)量:"+buyCount+"\t價格:"+price);
Map<String,Object> car = new HashMap<String, Object>();
//controller添加購物車對象的部分信息
car.put("uid",uid);
car.put("pdId",pdid);
car.put("gginfo",gginfo);
car.put("spCount",Integer.parseInt(buyCount));
car.put("price",price);
JSONObject json = new JSONObject();
try{
carSvs.save(car);
json.put("success","0");
}catch(RuntimeException e){
e.printStackTrace();
json.put("success","-1");
}
WebUtils.toJson(resp, json);
}
3. Service
- 根據(jù)Map集合中的商品id查到商家id
- 根據(jù)Map集合中的規(guī)格信息(11#22)和商品id查出商品價格和庫存和商品庫存id
- 在Map集合中繼續(xù)存入商家id,庫存id,商品價格,庫存數(shù)量,時間和購物車Id
- 調(diào)用Dao保存購物車信息
public void save(Map<String, Object> car) throws RuntimeException {
log.debug("");
//service添加購物車對象的其它一些查詢信息
String cmpId = prodDao.findProdCompanyId(car.get("pdId").toString());
log.debug("1..查詢 商家 id :"+cmpId);
String[] pcInfoArray = car.get("gginfo").toString().split("#");
log.debug("2...字規(guī)格個數(shù):"+pcInfoArray.length+"\t"+Arrays.toString(pcInfoArray));
Map<String,Object> pt = prodDao.findByPcInfo(car.get("pdId").toString(),pcInfoArray);
log.debug("3...查詢 ProdCount對象:"+pt);
car.put("comId",cmpId);
car.putAll(pt);
car.put("ggId",pt.get("pcid"));
car.put("joinTime", WebUtils.getFormatDate(new Date()));
car.put("carId",WebUtils.get32UUID());
//dao 保存購物車的全部信息
log.debug("3...保存購物車信息");
carDao.save(car);
}
時間轉(zhuǎn)換字符串
public static String getFormatDate(Date d){
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return fmt.format(d);
}
4. Dao
4.1 ProdDao
/**
* 根據(jù) 商品id 查詢 商家 id
* @param prodId
* @return
*/
public String findProdCompanyId(String prodId)throws RuntimeException;
/**
* 根據(jù) 商品 和 規(guī)格info 查詢規(guī)格對象
* @param string
* @param pcInfoArray
* @return
*/
public Map<String, Object> findByPcInfo(@Param("pid") String pid, @Param("infoArr") String[] infoArr)throws RuntimeException;
4.2 CarDao
/**
* 保存一個購物信息
* @param mp
* @throws RuntimeException
*/
public void save(Map<String,Object> mp)throws RuntimeException;
5. mapper.xml
5.1 ProdMapper.xml
<select id="findByPcInfo" resultType="Map">
select * from prodcount where prodid=#{pid}
<foreach collection="infoArr" item="ins">
and pcinfo like concat('%',concat(#{ins},'%'))
</foreach>
</select>
<select id="findProdCompanyId" resultType="String" parameterType="String">
select userid from product where pid =#{id}
</select>
5.2 CarMapper.xml
<insert id="save" parameterType="Map">
insert into spcar values(
#{carId},
#{uid},
#{pdId},
#{comId},
#{ggId},
#{pcinfo},
#{pcprice},
#{pccount},
#{spCount},
#{joinTime},
#{y1},
#{y2},
#{y3}
)
</insert>
購物車展示
思路:
- 購物車頁面加載完成時向服務(wù)端發(fā)送請求得到購物車表的數(shù)據(jù)
- Controller層需要JSON進行數(shù)據(jù)的封裝,
- 每個Map是一個商品信息,規(guī)格信息是
List<Map>
存到Map中 - 規(guī)格信息的Map中存子規(guī)格id和名稱父規(guī)格id和名稱,所有規(guī)格存到Map中
- 其中規(guī)格信息需要在service層進行#分割查詢
JSON存放格式:一組商品信息
{"success":"0",data:[
{
"carId": "8a683f60c3dc11e902012c86b718fe04",
"pdId": "a44",
"pcprice": "310.00",
"pname": "橙味芬達",
"pcCount": "10",
"comId": "kele003",
"cname": "可口可樂公司",
"spCount": "10",
"pcinfo": "72#76",
"infoData": [
{subName=罐裝, topName=包裝材料, topid=70, subid=72},
{subName=250ml, topName=容量, topid=75, subid=76}]
]
},
1. 頁面的請求
根據(jù)當前登陸的用戶的id進行查詢
$(function(){
//alert("111");
$.ajax({
url:"ctrl/users/carList.do?uid=${lged.userId}",
type:"get",
async:false,
success:function(dt){
2. Controller
- 用
List<Map>
存放所有商品的信息,調(diào)用service層的方法去查詢 - 對JSON數(shù)據(jù)進行封裝
@RequestMapping("/carList.do")
@ResponseBody
public void carList(@RequestParam String uid,HttpServletResponse resp)throws Exception{
log.debug("");
List<Map<String,Object>> carList = null;
JSONObject json = new JSONObject();
carList = carSvs.getCarByUserId(uid);
if(carList==null||carList.size()<0){
json.put("success","-1");
}
json.put("success","0");
json.put("data",carList);
log.debug(carList);
WebUtils.toJson(resp, json);
}
3. Service
- 調(diào)用Dao層的方法查詢購物車的信息
- 規(guī)格信息為11#22格式這里補全規(guī)格的信息
- 每一個商品的規(guī)格信息為
List<Map>
遍歷所有商品存到對應(yīng)的商品信息中 - 根據(jù)#進行分割得到規(guī)格id去查到規(guī)格對象,把名字和id存到Map中
public List<Map<String, Object>> getCarByUserId(String uid)
throws RuntimeException {
List<Map<String,Object>> carList = carDao.findCarByUserId(uid);
for(Map<String,Object> map:carList){
String[] sp = map.get("pcinfo").toString().split("#");
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
for(String s:sp){
Prodtypes ps = typeDao.findById(Integer.parseInt(s));
Prodtypes pf = typeDao.findById(typeDao.findById(Integer.parseInt(s)).getPupid());
Map<String,Object> info = new HashMap<String, Object>();
info.put("topid", pf.getPtpid());
info.put("topName", pf.getPtpname());
info.put("subid", ps.getPtpid());
info.put("subName", ps.getPtpname());
list.add(info);
}
map.put("infoData",list);
}
return carList;
}
4. Dao
4.1 CarDao
public List<Map<String, Object>> findCarByUserId(String uid)throws RuntimeException;
CarMapper.xml
<select id="findCarByUserId" parameterType="String" resultType="Map">
select
c.carId,
c.pdId,
p.pname,
(select img.pimgpath from productImgs img where img.prodid = c.pdId and img.pimgtype=20) pimg,
gg.pcinfo,
c.pcprice,
c.spCount,
c.pcCount,
c.comId,
uf.cname
from
spcar c,
prodcount gg,
product p,
companyinfo uf
where
c.pdId = p.pid
and c.ggId = gg.pcid
and c.comId = uf.uid
and c.uid =#{id}
order by c.joinTime desc, c.comId;
</select>
4.1 ProdTypesDao
public Prodtypes findById(int pid)throws RuntimeException;
ProdTypesMapper.xml
<select id="findById" resultType="myProType" parameterType="int">
select * from prodtypes where ptpid = #{pid}
</select>
5. 頁面信息獲取
$.each(dt.data,function(x,y){
遍歷所有商品信息用y.數(shù)據(jù)庫列名
獲取再嵌套一層循環(huán)遍歷規(guī)格信息用
y.infoData
存入List<Map>
集合的鍵map.put("infoData",list);
同一家商家的物品放到一起,這里做一個判斷
$.ajax({
url:"ctrl/users/carList.do?uid=${lged.userId}",
type:"get",
async:false,
success:function(dt){
alert(dt);
dt = eval("("+dt+")");
if(dt.success=='0'){
alert(dt.data.length);
var comName = "";
$.each(dt.data,function(x,y){
var str="";
//str+="<tr class='item-list02'>";
str+="<div class='bundle bundle-last '>";
if( comName != y.cname){
//alert('新公司');
comName = y.cname;
str+=" <div class='bundle-hd'>";
$.each(y.infoData,function(q,w){
str+=" <span class='sku-line'>"+w.topName+":"+w.subName+"</span>";
});
- 點擊添加商品數(shù)量的”+“或手動輸入時不能超過最大庫存,而且后面的金額要跟著變化
- 添加按鈕上增加點擊事件,傳入商品的購物車id和它的庫存
- 我們把要購買的商品數(shù)量標簽的id設(shè)為
t+carId
,這樣方便我們得到它的標簽對象
<input class='text_box' id='t"+y.carId+"' name='' xxyyzz='"+y.pcprice+"' type='text' value='"+y.spCount+"' style='width:30px;' onkeyUp='f4(\""+y.carId+"\","+y.pcCount+")' />
<input class='add am-btn' name='' type='button' value='+' onclick='f3(\""+y.carId+"\","+y.pcCount+")'/>
- 標簽的value值轉(zhuǎn)int-
parseInt( txt.val() )
- 標簽xxyyzz屬性的值轉(zhuǎn)為Float-
parseFloat( txt.attr("xxyyzz") )
- 保留兩位小數(shù)-
(num * pr).toFixed(2)
function f3(id,mx){
var txt = $("#t"+id); //添加按鈕對應(yīng)的 文本框
var num = parseInt( txt.val() );
console.log("num:"+num+" mx:"+mx + ( num >= mx ) );
num++;
if( num > mx){
//alert("最大了");
num=mx;
}
txt.val( num ); //最大值
f5(id);
}//
//手動輸入
function f4(id,mx){
var txt = $("#t"+id); //添加按鈕對應(yīng)的 文本框
var num = parseInt( txt.val() );
if( num > mx) txt.val( mx );
f5(id);
}//
//重新計算小計
function f5(id){
var txt = $("#t"+id);
var num = parseInt( txt.val() ); //獲取文本框的值
var pr = parseFloat( txt.attr("xxyyzz") );
console.log("num:"+num+" pr:"+pr + ( num * pr ) );
$("#e"+id).html( (num * pr).toFixed(2) );
}