本文介绍如何在JavaScript中通过Ajax将对象数组转换为JSON字符串传递给后端,并在Java后端使用request.getParameter获取该字符串,最后利用JSONArray.fromObject方法解析为对象列表。
前端JavaScript传递对象数组
前端JavaScript代码实现如下:
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格式的字符串,需使用方法。
后端Java接收与解析
后端接收处理逻辑如下:
String conditions = request.getParameter("conditions");
JSONArray conditionList = JSONArray.fromObject(conditions);
以上即为JS传递对象数组参数至后端及后端获取的完整实例代码,供参考使用。