springmvc sends and receives data by ajax request using json format

【0】README

1) springmvc sends or receives data by ajax request using json format;


【1】 ajax function

<script type="text/javascript">
		
		var checkoutUserlistIsAccess = false;
		$(document).ready(function(){	
			$("#first").hide();
			if(checkoutUserlistIsAccess==false) {
				checkoutUserlist(); // checkout user list.
			}
			
			/* bind event to input with id searched */
			/* $("#search").bind("click", function() {
				$("#second").hide();
				$("div[id^='first']").hide();
			});
			
			$("#search").bind("blur", function() {
				$("#second").show();
				$("div[id^='first']").hide();
			}); */
			
		});
		
		//ajax 访问函数
		var member;
		function checkoutUserlist(){
			checkoutUserlistIsAccess = true;
			var userid=1;
			// alert("request for user list by ajax.");
			var url = "<c:url value='/chat/userlist' />"; //请求的地址 
			$.post(url,{
					keyword:userid //[逗号 连接 ]
				},
				function(data){ // 回调函数 .
					member = data;
					for(var i=0; i<data.length; i++) {
						appendAIntoDiv("second_userlist", data[i]);
					}
				},"json"); 
		}
		
		// append <a> into a div.
		function appendAIntoDiv(objId, value) {
			$("#"+objId).append("<a href='<c:url value='/chat/single?touser=" 
					+ value + "'/>' class='list-group-item'>    " + value +"</a>");
		}		
		
	</script>

【2】method sending data via json format defined in springmvc controller

// ajax requests for user list (by json format).
	@RequestMapping(value="/userlist", method=RequestMethod.POST, produces="application/json")
	public @ResponseBody String checkoutUserlist() {
		List<String> list = repository.checkoutUserlist();
		ObjectMapper mapper = new ObjectMapper();
		try {
			String json_result = mapper.writeValueAsString(list);
			System.out.println(json_result);
			return json_result;
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return null;
		}
	}

【3】method receiving data via json format defined in springmvc controller




你可能感兴趣的:(springmvc sends and receives data by ajax request using json format)