1、添加JSON数据转换驱动
1、pom文件添加JSON依赖 <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.0</version> </dependency>2、全局配置文件添加驱动,使得可以调用JSON数据转化的类<mvc:annotation-driven/>(http://www.springframework.org/schema/mvc)
2、Cotroller类和响应的HTML
@Controllerclass A{ //返回字符串 @ReuqestMapping("/uri") @ResponseBody//设置为响应体 public String test01(){ return "String"; } //返回对象 @ReuqestMapping("/uri") @ResponseBody//设置为响应体 public Student test01(Student stu){ return stu; } //List @ReuqestMapping("/uri") @ResponseBody//设置为响应体 public List<Student> test01(List<Student> stus){ return stus; } }
3、示例
@Controllerpublic class TestClass { @RequestMapping(value = "/some.do",method = RequestMethod.POST) @ResponseBody public Student test01(Student student){ return student; } @RequestMapping(value = "/string.do",method = RequestMethod.POST,produces="application/json;charset=UTF-8")//设置返回内容为String,编码格式 @ResponseBody public String test03(){ return "student"; } @RequestMapping(value = "/other.do",method = RequestMethod.POST) @ResponseBody public List<Student> test02(){ List<Student> students = new ArrayList<>(); students.add(new Student(34,"name1")); students.add(new Student(234,"name2")); return students; }}
<meta charset="UTF-8"> <script type="text/javascript" src="js/jquery-3.4.1.js"></script> <script type="text/javascript"> $(function () { $("#a").click(function () { $.ajax({ url:"some.do", data:{ name:"历史", age:23, }, type:"post", dataType:"json", success: function (rep) { alert(rep.name+"\t"+rep.age) } }) }) $("#b").click(function () { $.ajax({ url:"string.do", type:"post", success: function (rep) { alert(rep) } }) }) $("#c").click(function () { $.ajax({ url:"other.do", type:"post", dataType:"json", success: function (rep) { $.each(rep,function (i,res) { alert(res.name+"\t"+res.age) }) } }) }) }) </script> <button id="a">点击1</button> <button id="b">点击2</button> <button id="c">点击3</button>