文件与1一样,多加了2个向服务器传ajax的方法
controller
package org.youlxb.controller;
import java.util.LinkedList;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.youlxb.bean.Department;
import org.youlxb.bean.Employee;
@Controller
@RequestMapping("employee")
public class EmployeeController {
@RequestMapping("setEmployee")
@ResponseBody
public String setEmployee(@RequestBody Employee employee){
System.out.println(employee);
return "success";
}
@RequestMapping("setDepartment")
@ResponseBody
public String setDepartment(@RequestBody Department dp){
System.out.println(dp);
return "success";
}
}
index.html文件
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>springMVC的ajax传参</title>
<style>
*{margin: 0; padding: 0}
html,body{position: relative; height: 100%; }
body{margin:0;padding:0; font:12px/14px "微软雅黑","宋体",Arial; color:#333; word-wrap:break-word;}
#console{position: absolute; bottom: 0; left: 0; padding: 20px; width: 100%; height: 200px; border: 2px solid #d2d2d2; overflow: scroll; box-sizing: border-box;z-index: 9999;}
</style>
</head>
<body>
<button id="btn1" type="button">获得employee</button>
<button id="btn2" type="button">获得department</button>
<button id="btn3" type="button">发送employee</button>
<button id="btn4" type="button">发送department</button>
<div id="console"></div>
</body>
<script type="text/javascript" src="../js/jquery-1.8.3.min.js"></script>
<script>
$(function(){
$("#btn1").on("click", function(e){
$.post("../employee/getEmployee", function(data){
print(JSON.stringify(data));
});
});
$("#btn2").on("click", function(e){
$.post("../employee/getDepartment", function(data){
print(JSON.stringify(data));
});
});
$("#btn3").on("click", function(e){
$.ajax({
type: "POST",
url: "../employee/setEmployee",
data: '{"name":"宵小","age":20,"gender":"男"}',
contentType: "application/json",
success: function(data){
print(data);
}
});
});
$("#btn4").on("click", function(e){
$.ajax({
type: "POST",
url: "../employee/setDepartment",
data: '{"name":"部门1","employeeList":[{"name":"宵小郎","age":20,"gender":"男"},{"name":"宵大郎","age":25,"gender":"男"}]}',
contentType: "application/json",
success: function(data){
print(data);
}
});
});
function print(data){
var console = $("#console")[0];
var str;
if((typeof data) === "object"){
str = JSON.stringify(data);
}else{
str = data;
}
console.innerHTML += "<p>" + str + "</p><br />";
}
});
</script>
</html>
这里我用$.post方法没有成功过,不知道为什么,还是写个全的$.ajax方法
总结:springMVC的数据传输还是非常方便的,可以大大提高编程效率