1. 程式人生 > >spring mvc ,Ajax實現資料互動

spring mvc ,Ajax實現資料互動

spring mvc  和ajax  實現資料互動 

 測試按鈕

  <input type="button" onclick="aaclick();" value="測試"/>

 function aaclick(){
	   var url = "${pageContext.request.contextPath}/user/ajaxtest.action";
	   var value =$("input[name='loginId']").val();
	   alert(value)
	   $.ajax({
		   url:url,
		   type:"POST",
		   data:"loginId="+value,
		    success:function(data){
			   if(data!=null){
				   // do someString 
				   alert(data)
			   }
		   } 
	   });
   }
spring mvc 控制器
@RequestMapping(value="/ajaxtest.action")
	@ResponseBody
	public Map<String , Object> ajax(HttpServletRequest request,HttpServletResponse response,@RequestParam("loginId")String idid){
		Map<String , Object> map = new HashMap<String, Object>();
		System.out.println(idid);
		/**
		 * do someString
		 * 
		 */
		UserInfoPO po =new UserInfoPO();
		List<UserInfoPO> list =userInfoService.queryList(po);
		map.put("list",list );
		log.info(map.toString());
		return map;
	}

或者通過json實現資料互動時

spring mvc 控制器 

@RequestMapping(value = "/classListAjax.action")
	public String classListAjax(HttpServletRequest request,
			HttpServletResponse response) {
		try {
       /**
        * 查出資料   傳到後臺
        */
			TGoodsClassPO po = new TGoodsClassPO();
			List<TGoodsClassPO> listName = tGoodsClassService.queryName(po);
			JSONArray json = new JSONArray();
			for (int i = 0; i < listName.size(); i++) {
				JSONObject jj = new JSONObject();
				jj.put("id", listName.get(i).getId());
				jj.put("name", listName.get(i).getClassName());
				json.add(jj);
			}

			response.getWriter().write(json.toString());
		} catch (IOException e) {

			e.printStackTrace();
		}
		return null;
	}

jsp 頁面總需要解析json資料
 function aaclick(){
	   var url = "${pageContext.request.contextPath}/user/classListAjax.action";
	   var value =$("input[name='loginId']").val();
	   alert(value)
	   $.ajax({
		   url:url,
		   type:"POST",
		   data:"loginId="+value,
		    success:function(data){
			   if(data!=null){
				   var json =eval("("+ data +")");// 解析json
				   for (var int = 0; int < json.length; int++) {
					alert (json[int].id  +  json[int].name)
				}
			   }
		   } 
	   });
   }