一:ajax傳遞List<String>類型的數據html
js代碼:java
- //聲明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代碼:ajax
- @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傳遞List<Obj>類型的數據json
後臺須要用到json解析工具,我選得是jacksonapp
導入jackson依賴:ide
- <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代碼:url
- @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傳遞任何複雜參數時,後臺能夠直接從流中來讀取數據進行解析xml
js代碼:htm
- //聲明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";
- }