前端向后端传数组的三种方式(第一种简洁,第二种正式,第三种很奇特)
方式1:直接传array,后端接收时,不通过参数接收,用request.getParameterValues方式获取(注意参数的写法)
var loginNameArray=[];
var accessArray=[];
loginNameArray.push(loginName);
accessArray.push(rval);
var data = {
"fileParams": fileParams,
"loginNameArray": loginNameArray,
"accessArray": accessArray
};
$.post(
url,
data,
);
后端
aa(Model model, String fileParams, HttpServletRequest request) {
String[] loginNameArray = request.getParameterValues("loginNameArray[]");
String[] accessArray = request.getParameterValues("accessArray[]");
}
方式2,后端接收参数用@RequestParam("testObjs[]")List<Integer> testObjs获取
var testObjs = [];
testObjs.push(1);
testObjs.push(2);
var data = {
"testObjs": testObjs
};
$.post(
"file/objectArrayPostTest",
data,
function (res) {
},
"Json"
); //post
//后端
public void objectArrayPostTest(Model model, @RequestParam("testObjs[]")List<Integer> testObjs) {
// public void objectArrayPostTest(Model model, @RequestParam("testObjs[]")TestObj[] testObjs) {
System.out.println();
}
方式3:前端传array的string,后端通过String[]类型参数接收
<input type="hidden" name="ids" id="ids" />
var ids = [];
var items = $("[name=prIds]:checkbox:checked");
items.each(function (index, item) {
var id = item.value;
if (id != null) ids.push(id);
});
$("#ids").val(ids);
var data = {
"ids": $('#ids').val(),
"access": access
};
后端
bb(Model model, String[] ids)