在使用ajax進行請求,並傳遞參數時,偶爾需要把數組作為傳遞參數,這是就要使用@RequestBody來解決這個問題
在頁面端的處理:
(1)利用JSON.stringify(arr)需要把json對象數組轉變成一個json對象字符串
(2)在ajax的參數中設置"contentType": "application/json"
$(function(){ $("#exe").on("click",function(){ var arr = new Array(); arr.push({"name":"lcs","age":18}); arr.push({"name":"yds","age":19}); arr.push({"name":"hrl","age":20}); arr.push({"name":"lyf","age":21}); var arrs = JSON.stringify(arr); $.ajax({ "url": "ajax_array.do", "type": "post", "data": arrs, "contentType": "application/json", "dataType": "json", "success": function(result){ alert("請求成功!"); }, "error": function(){ alert("請求失敗!"); } }); }); });
在后端的處理:
(1)利用RequestBody來接收JSON對象字符串,persons中是json對象數組進JSON.stringify(arr)轉換的JSON對象字符串(數組的json對象字符串)
(2)導入json-lib,利用其JSONArray和JSONObject的方法來解析獲取JSON對象字符串中的數據
(3)JSONArray.fromObject(persons)是把JSON對象字符串轉換成JSON對象。
@ResponseBody @RequestMapping("/ajax_array.do") //@RequestBody接收ajax請求的json字符串參數
public String getPersons(@RequestBody Person[] persons){ //將persons JSON字符串轉換成JSON對象 //JSONArray對象,有點像list對象
JSONArray arrs = JSONArray.fromObject(persons); List<Person> personList = new ArrayList<Person>(); //遍歷JSONArray
for(int i=0; i<arrs.size(); i++){ Person person = new Person(); //getJSONObject(i)是一個json對象
String name = arrs.getJSONObject(i).getString("name"); int age = arrs.getJSONObject(i).getInt("age"); person.setName(name); person.setAge(age); personList.add(person); } System.out.println(personList); return "success"; }