1.加入jackson的jar包
2.在响应的方法上加上@ResponseBody:把java对象转化为json对象
3.方法的返回值可以是对象集合字符串
<script type="text/javascript" src="js/jquery-3.4.1.min.js"></script> <script type="text/javascript"> $.post("ajax/Ajax1",{"name":"zhu"},function(data){ $.each(data,function(i,n){ alert(n.name); }) }) </script>
可以返回字符串
@RequestMapping(value="Ajax1",produces = "text/html;charset=UTF-8") @ResponseBody public String ajax1(String name) { System.out.println(name); return "hello胡"; }
也可以返回对象
@RequestMapping("Ajax2") @ResponseBody public User ajax2(String name) { User user=new User("胡昊中","1"); return user; }
还可以返回集合
@RequestMapping("Ajax3") @ResponseBody public List<User> ajax3(String name) { User user1=new User("胡昊中","1"); User user2=new User("朱华龙","2"); User user3=new User("王玉峰","3"); List<User> list=new ArrayList<>(); list.add(user1); list.add(user2); list.add(user3); return list; }
在返回字符串时,如果输入汉字会出现乱码,解决方法如下
1. 更改@RequestMapping
@RequestMapping(value="Ajax1",produces="text/html;charset=UTF-8")
2. 在springMVC配置文件中通过org.springframework.web.servlet.view.InternalResourceViewResolver类重写代码编码。
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg index="0" value="utf-8"></constructor-arg>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>