1. 程式人生 > >springMVC利用json傳資料到前臺(二)

springMVC利用json傳資料到前臺(二)

本文是本人在學習網路視訊springMVC的過程中的學習筆記。

本文是記錄從後臺傳到前臺的過程。

@RequestMapping(value="/addUserJson")
	public String addUserJson(User user,HttpServletRequest request,HttpServletResponse response){
		String result = "{\"userName\":\""+ user.getUserName() +"\",\"age\":\" "+ user.getAge()+" \"}";
		PrintWriter out = null;
		response.setContentType("application/json");
		
		try {
			out = response.getWriter();
			out.write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "userManager";
	}
	

前臺接收部分
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
   
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="/springMVC6/js/jquery-1.7.1.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
	$(document).ready(function(){
		$("#add").click(function(){
			var userName = $("#userName").attr("value");
			var age =$("#age").attr("value");
			
			var user = {userName:userName,age:age};
			
			$.ajax({
				url:"/springMVC6/user/data/addUserJson",
				type:"post",
				data:user,
				success:function(data){
					alert("userName--->" + a.userName + "age--->" + a.age );
					
				}
			});
			
			
			
		});
	});
</script>
</head>
<body>
	<h>json新增使用者</h>
	姓名:<input type="text" id="userName" name="userName">
	年齡:<input type="text" id="age" name="age">
	<input type="button" id="add" value="新增">
	
</body>
</html>