一、ajax默认与服务器交互,采用json格式。导入JAR包jackson
jackson-annotations-2.9.8.jar
jackson-core-2.9.8.jar
jackson-databind-2.9.8.jar
二、使用jquery
body中使用控件:
<input type="button" value="testJson" id="testJson" />
<head></head>中为控件添加事件响应
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#testJson").click(function(){
$.post(
"handler/testJson",
{"stuName":"test","stuAge":22,"stuNo":5},
function(result){
for(var i=0;i<result.length;i++){
alert(result[i].stuName);
}
}
)
})
})
</script>
三、后端servlet中使用@ResponseBody,告诉spring mvc ,此时的返回值不是一个View页面,而是直接写入 HTTP response body 中
@ResponseBody//告诉spring mvc ,此时的返回值不是一个View页面,而是直接写入 HTTP response body 中,以json格式传输给前端
@RequestMapping("testJson")
public List<Student> testJson(Student student){
Student stu1=new Student();
stu1.setStuNo(1);
stu1.setStuName("zzz");
stu1.setStuAge(28);
List<Student> students=new ArrayList<>();
students.add(student);
students.add(stu1);
return students;
}