Rumah >pembangunan bahagian belakang >tutorial php >ajax传递list集合详解
本文主要和大家分享ajax传递list集合详解,希望能帮助到大家。
一:ajax传递Listf7e83be87db5cd2d9a8a0b8117b38cd4类型的数据
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"; }
二:ajax传递List29d5c1fc0a9a7d5f78ab971caa06e684类型的数据
后台需要用到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); } });
java代码:
@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"; }
Atas ialah kandungan terperinci ajax传递list集合详解. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!