Jquery Ajax實現購物車的數量加減按鈕功能

實現購物車的數量加減按鈕功能


具體實現:使用jquery Ajax與Servlet交互

HTML模塊

<table id="tab">
<tr>
<td>
<input type="button" value="-" onclick="jian();" style="width:30px; height:28px;" />
<input id="num" name="num" value="1" readonly="readonly" style="width:64px;height:25px; text-align:center;"/>
<input type="button" value="+" onclick="add();"style="width:30px; height:28px;" />
</td>
</tr>
</table>

Jqery Ajax模塊

導入jqery-3.3.1.min.js包

<script src="${ctx }/js/jquery-3.3.1.min.js"></script>
<script>
function add(){
	var text=$("#num").val();
	var config={
		"url":"/Shop/addServlet",
		"async":false,
		"type":"post",
		"dataType":"text",
		"data":{
			"text":text,
		},
		"success":function(result){
			$("#num").val(result);
		},
		"error":function(xhr,status,error){
			
		}
};
	$.ajax(config);
}
function jian(){
	var config={
			"url":"/Shop/jianServlet",
			"async":false,
			"type":"post",
			"dataType":"text",
			"data":{
				"text":$("#num").val(),
			},
			"success":function(result){
				$("#num").val(result);
			},
			"error":function(xhr,status,error){
				
			}		
	};
	$.ajax(config);
}
</script>

Servlet模塊

addServlet


    	String text=request.getParameter("text");
		if(!text.equals("")&&text!=null) {
			int num=Integer.parseInt(text);
			int sum=num+1;
			response.getWriter().write(String.valueOf(sum));
			return;
		}

jianServlet

String text=request.getParameter("text");
		if(!text.equals("")&&text!=null) {
			int num=Integer.parseInt(text);
			int sum=1;
			if(num>1) {
			sum=num-1;
			}
			response.getWriter().write(String.valueOf(sum));
			return;
		}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章