1. 程式人生 > >JQuery中AJAX的案列使用

JQuery中AJAX的案列使用

Servlet 中的程式碼如下

  private static final long serialVersionUID = 1L;
	CakeService service =new CakeServiceImpl();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		int pageSize=8;
		int index=1;//起始頁
		int total=service.getPages(pageSize);
		String page=req.getParameter("page");
		if(page!=null && !"".equals(page.trim())){
			index=Integer.parseInt(page);
		}
		
		List<Cake> list=service.getListByPages(index, pageSize);
		
		Gson g=new Gson();
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("total", total);
		map.put("curPage", index);
		map.put("list", list);
		String strMap=g.toJson(map);
		resp.getWriter().print(strMap);
		
	}
$.ajax({
		type:"post",//提交方式
		url:"../CakeServlet",//請求路徑
		async:false,//同步提交,非同步為true
		data:{//json格式傳遞引數
			page:page
		},
		dataType:"json",//返回資料型別json
		success:function(obj){//obj為返回資料json型別的物件,success判斷是否有資料返回
			//console.log(obj);
			//從json中拿出資料並賦值
			curPage=obj.curPage;
			total=obj.total;
			
		 	ul.empty();
			$("#abox").empty();
			for(i in obj.list){
				var item=obj.list[i];
				var li="<li class='product-li'><div class='product-div'><div class='picture'><img src='"+item.Cake_img+"' /></div><div class='text1'><h1>"+item.Cake_Englishname+" <br /> "+item.Cake_Chinesename+"</h1><p>"
				+item.Cake_describe+"</p><h2>¥ "+item.Cake_price+"/1.2 "+item.Cake_unit+"<a class='clickbuy' href='../CakedetailServlet?img="+item.Cake_img+"&cakeid="+item.Cake_id+"'>立即購買</a></h2></div></div></li>";
				ul.append(li);
			}
		var a=""; 
		for(var j=1;j<=obj.total;j++){
			//顯示頁碼並實現點選重新整理頁面商品
			a=a+"<a onclick='sendPageAjax("+j+")'>"+j+"</a>";
		}
		
		var el="<a id='pre'>上一頁</a>"+a+"<a id='next'>下一頁</a>";
 		$("#abox").append(el);
 		
 		
 		
		}
	});