原文链接:http://blog.csdn.net/qq_37936542/article/details/79277495
一:ajax传递List<String>类型的数据
js代码:
- //声明list
- var _list = [];
- //放入string对象
- for (var i = 0; i < 3; i++) {
- _list[i]="tom";
- }
- $.ajax({
- url : '/ajax/test',
- data : "list="+_list,
- type : "POST",
- success : function(data) {
- alert(data);
- }
- });
java代码:
- @RequestMapping(value="test",method=RequestMethod.POST)
- @ResponseBody
- public String ajaxList(@RequestParam("list")List<String> strList){
- for (String str : strList) {
- System.out.println(str);
- }
- return "OK";
- }
后台需要用到json解析工具,我选得是jackson
导入jackson依赖:
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- <version>2.7.3</version>
- </dependency>
js代码:
- //声明list
- var _list = [];
- //创建两个user对象
- var a= {};
- a.name="tom";
- a.age=23;
- a.city="上海";
- var b = {};
- b.name="jack";
- b.age=25;
- a.city="安徽";
- //将user放入_list
- _list.push(a);
- _list.push(b);
- $.ajax({
- url : '/ajax/test1',
- data : "list="+JSON.stringify(_list),
- type : "POST",
- success : function(data) {
- alert(data);
- }
- });
- @RequestMapping(value="test",method=RequestMethod.POST)
- @ResponseBody
- public String ajaxList(@RequestParam("list")String userList) throws Exception{
- //jackson对象
- ObjectMapper mapper = new ObjectMapper();
- //使用jackson将json转为List<User>
- JavaType jt = mapper.getTypeFactory().constructParametricType(ArrayList.class, User.class);
- List<User> list = (List<User>)mapper.readValue(userList, jt);
- return "OK";
- }
三:当ajax传递任何复杂参数时,后台可以直接从流中来读取数据进行解析
js代码:
- //声明list
- var _list = [];
- //创建两个user对象
- var a= {};
- a.name="tom";
- a.age=23;
- a.city="上海";
- var b = {};
- b.name="jack";
- b.age=25;
- a.city="安徽";
- //将user放入_list
- _list.push(a);
- _list.push(b);
- $.ajax({
- url : '/querz/test',
- data : JSON.stringify(_list),//这里需要json化
- type : "POST",
- success : function(data) {
- alert(data);
- }
- });
java代码:
- @RequestMapping(value="test",method=RequestMethod.POST)
- @ResponseBody
- public String ajaxList(HttpServletRequest request) throws Exception{
- //从流中读取数据
- BufferedReader br = request.getReader();
- String str = "";
- StringBuffer sb = new StringBuffer();
- while((str = br.readLine()) != null){
- sb.append(str);
- }
- ObjectMapper mapper = new ObjectMapper();
- //使用jackson解析数据
- JavaType jt = mapper.getTypeFactory().constructParametricType(ArrayList.class, User.class);
- List<User> list = (List<User>)mapper.readValue(sb.toString(), jt);
- System.out.println(list);
- return "OK";
- }
文末福利:
福利一:前端,Java,产品经理,微信小程序,Python等资源合集大放送:https://www.jianshu.com/p/e8197d4d9880
福利二:微信小程序入门与实战全套详细视频教程:https://www.jianshu.com/p/e8197d4d9880
领取方式:
如果需要学习视频,欢迎关注 【编程微刊】微信公众号,回复【领取资源】一键领取以下所有干货资源,获取更多有用技术干货、文档资料。所有文档会持续更新,欢迎关注一起成长!