前端:組裝資料並送出
var conditons = [];
var test1 = new Object();
test1.name = "1";
test1.id = "2";
var test2 = new Object();
test2.name = "1";
test2.id = "2";
conditons.push(test1);
conditons.push(test2);
$(function(){
$.ajax({
async: "false",
type: 'post',
url: '鏈接',
data: { name: "123", conditions: JSON.stringify(conditons) },
dataType: 'json',
success: function(data){ console.log(data); },
error: function (XMLHttpRequest, textStatus, errorThrown){ alert("error"); }
});
});
整段的重點只有一個:用 JSON.stringify 把物件陣列轉成字串再送。因為傳統表單只能傳 key-value 形式的資料,直接塞陣列進去會變成 [object Object]。
後端:還原成集合物件
String conditions = request.getParameter("conditions");
JSONArray conditionList = JSONArray.fromObject(conditions);
取出字串後,用 JSON 函式庫反序列化就能拿回清單,後續照常做查詢或驗證。
一是 async: "false" 會讓瀏覽器同步等待,畫面在請求返回前會凍結,現代做法應該保持非同步,並把後續邏輯寫在 success 裡。二是資料量大的時候,字串塞在表單欄位裡會碰到長度限制,這種情況改用 contentType: 'application/json' 並直接把物件放進 data 會更乾淨:
$.ajax({
url: '/api/conditions',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ name: "123", conditions: conditons }),
success: function (res) { console.log(res); }
});
三是無論哪種方式,後端收到字串後都應該做格式與欄位驗證再使用,避免 malformed JSON 造成例外。