前言
-最近开发遇见了不少前端传个数组,后端接口怎么接都接收不到的情况,特此总结一下。
-这一篇总结简单的数组,如var array=[1,2,3]
-复杂的数组对象在下一篇 总结: 前后端传参(二)之数组对象 [点击跳转](https://blog.csdn.net/shuai8624/article/details/106044141)
一. 示例采用的技术
前端: jquery, ajax请求(axios应该也差不多,自己看着玩)
后端: SpringBoot
二. 直接上才艺
总共总结了五种方式:
1)将参数拼接到url后面
前端:
//http://localhost:8080/singleArray?ids=1&ids=2&ids=3
//方式一:将参数拼接到url后面
function singleArray1() {
let array=[1,2,3];
let url= "http://localhost:8080/singleArray?";
array.forEach(item=>{
url+="ids="+item+"&";
});
$.ajax({
url: url,
data: {},
type: "post",
dataType: "json",
success: function (data) {
alert(data)
},
})
};
后端接口:
@RequestMapping("/singleArray")
public Integer singleArray(Integer[] ids){
return ids.length;
}
2)前端传array,后端接口参数增加注解@RequestParam(“ids[]”) Integer[] ids
前端:
//方式二:直接传array,后端接口参数增加注解@RequestParam("ids[]") Integer[] ids
//contentType为默认值,即 application/x-www-form-urlencoded
//不可用 contentType:"application/json", 直接400错误
function singleArray2() {
var array=[1,2,3];
$.ajax({
url: "http://localhost:8080/singleArray2",
data: {
"ids": array
},
type: "post",
dataType: "json",
success: function (data) {
alert(data)
},
})
};
后端:
@RequestMapping("/singleArray2")
public Integer singleArray2(@RequestParam("ids[]") Integer[] ids){
return ids.length;
}
3)前端转成json字符串, 后端接口String去接收,然后再转成json数组
前端:
//方式三:转成json字符串, 后端接口string去接收,然后再转成JSON数组处理
//contentType为默认值,即 application/x-www-form-urlencoded
//不能加contentType:"application/json",否则后台接收到的是null
function singleArray3() {
var array=[1,2,3];
$.ajax({
url: "http://localhost:8080/singleArray3",
data: {
"ids": JSON.stringify(array)
},
type: "post",
dataType: "json",
success: function (data) {
alert(data)
},
})
};
后端:
@RequestMapping("/singleArray3")
public String singleArray3(String ids){
return ids;
}
4)通过特殊字符拼接成字符串, 后端接口string去接收,然后再按特殊字符切割
前端:
//方式四:通过特殊字符拼接成字符串, 后端接口string去接收,然后再按特殊字符切割
//contentType为默认值,即 application/x-www-form-urlencoded
//不能加contentType:"application/json",否则后台接收到的是null
function singleArray4() {
var array=[1,2,3];
$.ajax({
url: "http://localhost:8080/singleArray3",
data: {
"ids": array.join("_")
},
type: "post",
dataType: "json",
success: function (data) {
alert(data)
}
})
};
后端: 跟第三个一样
@RequestMapping("/singleArray4")
public void singleArray4(String ids){
System.out.println("ids>>>"+ids);
}
5)前台整个data直接传 json字符串,后台接口用@RequestBody List ids 接收
前端:
//方式五: 前台整个data直接传 json字符串,后台接口用@RequestBody List<Integer> ids 接收
//contentType必须值为: "application/json"
function singleList1() {
var array=[1,2,3];
$.ajax({
url: "http://localhost:8080/singleList",
data: JSON.stringify(array),
type: "post",
dataType: "json",
contentType:"application/json",
success: function (data) {
alert(data)
},
})
};
后端:
@RequestMapping("/singleList")
public Integer singleList(@RequestBody List<Integer> ids){
return ids.size();
}
//或者
@RequestMapping("/singleList")
public Integer singleList(@RequestBody Integer[] ids){
return ids.length;
}
三. 注意
1、contentType别传错了,示例中没传的,使用的是默认值:application/x-www-form-urlencoded
2、如果遇到别的问题或者别的解决方法,可以联系我一下,做个补充