1. 程式人生 > >圖書購買系統之本地新增購物車(完善版)--實現生成訂單和子訂單

圖書購買系統之本地新增購物車(完善版)--實現生成訂單和子訂單

//購物車動態新增購物車資訊
$(function(){
	//1.從localStorage獲取購物資訊
	var books = localStorage.getItem("carts");
	var bookArr = JSON.parse(books);//將獲取到的字串存放進陣列中
	//2.宣告一個html用來拼接頁面
	var html = "";
	html +=	"<table id='cart' class='table text-center'>";
	html +=		"<tr class='danger'>";
	html +=			"<th class='text-center'>序號</th>";
	html +=			"<th class='text-center'>商品名稱</th>";
	html +=			"<th class='text-center'>價格</th>";
	html +=			"<th class='text-center'>購買數量</th>";
	html +=			"<th class='text-center'>庫存</th>";
	html +=			"<th class='text-center'>小計</th>";
	html +=		"</tr>";
	//3.遍歷陣列
	for(var i = 0;i < bookArr.length;i++){
		//獲取一本書
		var abook = bookArr[i];
		//將書本的資訊填到表格中
		html +=	"<tr>";
		html +=		"<td>"+i+"</td>";
		html +=		"<td>"+abook.name+"</td>";
		html +=		"<td>"+abook.price+"</td>";
		html +=		"<td><a class='glyphicon glyphicon-minus-sign' onclick='subBuyNum(this)'></a>"+abook.buynum+"<a class='glyphicon glyphicon-plus-sign' onclick='addBuyNum(this)'></a></td>";
		html +=		"<td>"+abook.num+"</td>";
		html +=		"<td>"+abook.price*abook.buynum+"</td>";
		html +=	"</tr>";
	}
	html +=	"</table>";
	$("#cartable").html(html);
});
//點選減號按鈕
function subBuyNum(caller){
	calFunction(caller,"sub");
}
//點選加號按鈕
function addBuyNum(caller){
	calFunction(caller,"add");
}
//優化程式碼
function calFunction(caller,tag){
	//得到當前呼叫者的父節點
	var $parent = $(caller).parent();
	//得到當前呼叫者的父節點的下一個兄弟
	var $bro = $(caller).parent().next();
	//找到父節點的文字資訊
	var buyNum = parseInt($parent.text());
	var num = parseInt($bro.text());
	//判斷當前是+還是-
	if(tag == "sub"){
		//減號
		if(buyNum>=2){
			buyNum--;
			num++;
		}
	}
	//加號
	else{
		buyNum++;
		num--;
	}
	//4.拼接html資訊,把html放到parent中
	var html = "";
	html += "<a class='glyphicon glyphicon-minus-sign' onclick='subBuyNum(this)'></a>"+buyNum+"<a class='glyphicon glyphicon-plus-sign' onclick='addBuyNum(this)'></a>";
	$parent.html(html);

	$bro.html(num);
	
	//5.找到價格元素的資訊
	var $price = $parent.prev();
	var price = parseFloat($price.text());
	
	//6.修改小計元素的資訊
	var $lastB = $parent.next().next();
	$lastB.text(price*buyNum);
	
	//7.修改總計元素的資訊
	calTotal();
	
	//8.修改本地購物車的數量
	//8.1找到序號數列
	var $first = $parent.parent().children(":first-child");
	var n = parseInt($first.text());
	modiyBuyNum(n,buyNum,num);
}

//計算當前購物車的總價格
function calTotal(){
	var $totalPrice = $("#totalprice"); 
	//找到table裡面的tbody,其實table的所有正文資訊都放在tbody裡面
	var $table = $("#cart").children();
	var $children = $table.children(":not(:first)");
	var $rowprices = $children.children(":last-child");
	var totalp = 0;
	$rowprices.each(function(){
		var p = parseFloat($(this).text());
		totalp += p;
	})
	$totalPrice.text("總計:"+totalp);
}

//頁面一載入就計算總計購物車的總價資訊
$(function(){
	calTotal();
})
//修改本地購物車的數量
function modiyBuyNum(idx,buynum,num){
	//1.獲取本地購車的資料(字串)
	var books = localStorage.getItem("carts");
	//2.把字串轉換為陣列物件
	var bookArr = JSON.parse(books);
	//3.從陣列中獲取指定idx的資料
	var abook = bookArr[idx];
	//4.修改這條資料
	abook.buynum = buynum;
	abook.number = num;
	//5.重新儲存購物車
	var booksStr = JSON.stringify(bookArr);
	localStorage.setItem("carts",booksStr);
}


//表單驗證的方法,使用bootstrapValidator外掛來完成
$(function(){
	$("#orderform").bootstrapValidator({
		feedbackIcons : {
			valid : 'glyphicon glyphicon-ok',
			invalid : 'glyphicon glyphicon-remove',
			validating : 'glyphicon glyphicon-refresh'
		},
		fields : {
			receiverAddress : {
				validators : {
					notEmpty : {
						message : '地址不能為空'
					},
					stringLength : {
						min : 2,
						max : 18,
						message : '地址必須在2到18位之間'
					}
				}
			},
			receiverName : {
				validators : {
					notEmpty : {
						message : '姓名不能為空'
					},
					stringLength : {
						min : 2,
						max : 18,
						message : '姓名長度必須在2到18位之間'
					}
				}
			},
			receiverPhone : {
				validators : {
					notEmpty : {
						message : '電話不能為空'
					},
					regexp : {
						regexp : /^1[0-9]{10}$/,
						message : '電話格式不正確'
					}
				}
			}
		}
	}).on("success.form.bv", function(e) {
		/*alert("sucess");*/
	});
});
//在購物車沒有資料、使用者沒有輸入送貨地址等資訊的情況下,不需要檢查使用者的登入情況(不需要傳送ajax)
$(function(){
	$("#submitform").click(function(){
		//1.從localStorage獲取所存的購物車資訊
		var books = localStorage.getItem("carts");
		var bookArr = JSON.parse(books);
		//2.如果bookArr不存在或者資料長度為0,則不允許提交表單
		if(bookArr == null){
			return false;
		}
		if(bookArr.length == 0){
			return false;
		}
		//3.如果輸入框沒有內容,禁止提交表單
		var inputisnull = false;
		$(":text").each(function(){
			if($(this).val().length == 0){
				inputisnull = true;
			}
		});
		if(inputisnull == true){
			alert("請輸入地址,收貨人和電話");
			return false;
			
		}
		//4.使用Ajax檢查使用者是否登入
		var sendUrl = contextPath+"/AjaxCheckIsLoginServlet?time="+new Date().getTime();
		$.ajax({
			type:"post",
			url:sendUrl,
			asasync:true,
			//請求成功回撥函式
			success:function(backData,textStatus,xmlHttpRequest){
				if(backData == "yes"){
					//提交訂單
					commitOrder();
				}
				//如果使用者沒有登入
				else{
					alert("sdfsdf");
					//顯示登入頁面
					showLoginPage();
				}
			}
		});
		return false;
	});
});
//傳送ajax請求,提交訂單
function commitOrder(){
	//1.從localStorage獲取所存的購物車資訊
	var orderitems = localStorage.getItem("carts");
	//2.傳送ajax請求,訂單提交資料
	var sendUrl = contextPath+"/AjaxMakeOrderServlet?"+"time"+new Date().getTime()+"&totalprice="+$("#totalprice").text().substr(3);
	$.ajax({
		type:"post",
		url:sendUrl,
		data:{
			"orderitems":orderitems,
			"receiverAddress":$("#receiverAddress").val(),
			"receiverName":$("#receiverName").val(),
			"receiverPhone":$("#receiverPhone").val()
		},
		async:true,
		success:function(backData,textStatus,xmlHttpRequest){
			var jsonobj = JSON.parse(backData);
			if("success" == jsonobj.status){
				//清空購物車
				localStorage.removeItem("carts");
				//跳轉頁面 
				window.location.href = contextPath+"/foreground/cart/makeordersuccess.jsp?orderid="+jsonobj.orderid+"&totalprice="+jsonobj.totalprice;
			}
		}
	});
}
//顯示登入彈出的模態框
function showLoginPage(){
	alert("OK");
	var html = ""; 
	html+="<div>";
	html+=	"<div class='modal fade' tabindex='0' id='myModal2'>";
	html+=	  	"<div class='modal-dialog' >";
	html+=	    	"<div class='modal-content'>";
	html+=	      		"<div class='modal-header text-center'>";
	html+=	        		"<button type='button' class='close' data-dismiss='modal'><span>×</span></button>";
	html+=	        		"<h4 class='modal-title'>使用者登入</h4>";
	html+=	      		"</div>";
	html+=	      		"<div class='modal-body paddingtop'>";
	html+=					"<p class='text-danger text-center' id='loginmsg'></p>"
	html+=	        		"<form id='loginform' class='form-horizontal'>";
	html+=	        			"<div class='form-group'>";
	html+=        					"<label for='name' class='col-md-4 control-label'>使用者名稱</label>";
	html+=							"<div class='col-md-4'>";
	html+=						    	"<input type='text' class='form-control' name='name' id='name' placeholder='請輸入使用者名稱'>";
	html+=						    "</div>";
	html+=	        			"</div>";
	html+=	        			"<div class='form-group'>";
	html+=						    "<label for='pass' class='col-md-4 control-label'>密碼</label>";
	html+=						    "<div class='col-md-4'>";
	html+=						      	"<input type='password' class='form-control' id='pass' name='pass' placeholder='請輸入密碼'>";
	html+=							"</div>";
	html+=						"</div>";				  
	html+=				 		"<div class='form-group text-center'>";
	html+=				   			"<input type='button' onclick='submitlogin()' class='btn btn-success' style='width: 200px;' value='登入'/>";
	html+=				 		"</div>";
	html+=	        		"</form>";
	html+=	    		"</div>";
	html+=  		"</div>";
	html+=		"</div>";
	html+=	"</div>";
	html+="</div>";
	$("#showloginform").html(html);
	$("#myModal2").modal('show');
}
//使用者在彈出登入框中輸入使用者密碼,提交表單的事件
function submitlogin(){
	var formData = $("#loginform").serialize();
	var sendUrl = contextPath+"/AjaxDoCartLoginServlet?&time="+new Date().getTime();
	$.ajax({
		type:"post",
		url:sendUrl,
		data:formData,
		async:true,
		success:function(backData,textStatus,xmlHttpRequest){
			if("success" == backData){
				$("#loginmsg").html("登入成功,3秒後跳轉頁面");
				var time = setInterval(function(){
					clearInterval(time);
					//提交order表單資料,生成訂單
					commitOrder();
				},3000);
			}
			else{
				//提示登入出錯資訊
				$("#loginmsg").html(backData);
			}
		}
		
	});
}

4.makeordersuccess.jsp,訂單提交成功頁面