1、controller
@RequestMapping("/postList") @ResponseBody public String postList(@RequestBody List<TestL> testL){ System.out.println(testL); return null; }
需要注意點:參數前面必須有注解 @RequestBody
2、ajax請求
var testList=[]; var user={}; user.id=1; user.name='jack'; testList.push(user); var user2={}; user2.id=2; user2.name='tom'; testList.push(user2); $.ajax({ // headers必須添加,否則會報415錯誤 headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, type: 'POST', dataType: "json", //表示返回值類型,不必須 data: JSON.stringify(testList), url: '/test/postList', success: function(){ alert('success'); } });
需要注意點:1、參數是數組類型
2、傳入data時,轉換 JSON.stringify(testList)
3、必須有headers: {
'Accept': 'application/json', 'Content-Type': 'application/json' }
最后再看下TestL類,沒有特別之處(不用包裝)。
public class TestL { private Integer id; private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }