前端:
1.生成數(shù)組
function getIds() {
var info = [];
$("input[name=checkbox1]:checked").each(function () {
if ($(this).attr("name") !== "th") {
info.push($(this).val());
}
});
return info;
}
2.ajax
var info = getIds();
$.ajax({
url: 'xxx',
type: 'POST',
dataType: "json",
async: false,
data: {
'type': 'type',
'ids': info
},
success: function (result) {
alert(result.message);
},
error: function (result) {
alert(result.message);
}
});
后臺(tái):
@PostMapping("/xxx")
@ResponseBody
public Map<String, Object> xxx(@RequestParam(value = "ids[]") Integer[] ids,@RequestParam String type) {
xxxx
return map;
}
用開發(fā)者工具查看傳遞的參數(shù)為:
image.png
這里用幾個(gè)地方要注意:
- ajax這里不能加contentType,因?yàn)閭鞯牟皇莏son
contentType: 'application/json;charset=utf-8',
2.后臺(tái)接收傳遞的數(shù)組參數(shù)名為ids[],所以后臺(tái)接收不能是下面這個(gè),下面這個(gè)參數(shù)名是ids.
@RequestParam Integer[] ids
3.后臺(tái)接收類型Integer[]
也可以是String[]
或者是List<Integer>
和List<String>
,但是參數(shù)名必須對(duì).
4.如果后臺(tái)接收的參數(shù)名想要設(shè)置為@RequestParam Integer[] ids
,則需要在ajax那里'ids': info
要改為'ids': info+''
,下面是改了ajax里參數(shù)后,傳遞到后臺(tái)的參數(shù)名,如圖.
image.png
5.如果后臺(tái)接收不到,說明參數(shù)有錯(cuò)誤,可以用開發(fā)者工具查看傳遞到后臺(tái)的參數(shù)名是什么.
單獨(dú)傳一個(gè)數(shù)組的情況下也可以這么傳:
1.生成數(shù)組
function getIds() {
var info = [];
$("input[name=checkbox1]:checked").each(function () {
if ($(this).attr("name") !== "th") {
info.push($(this).val());
}
});
return info;
}
2.ajax
var info = getIds();
$.ajax({
url: 'xxx',
type: 'POST',
dataType: "json",
data: JSON.stringify(info),
contentType: 'application/json;charset=utf-8',
success: function (result) {
alert(result.message);
},
error: function (result) {
alert(result.message);
}
});
3.后臺(tái)
@PostMapping("/xxx")
@ResponseBody
public Map<String, Object> xxx(@RequestBody Integer[] ids) {
xxx
return map;
}
注意的是:
1.這里ajax傳參數(shù)的時(shí)候,用了一個(gè)contentType
,設(shè)置為json
.所以data
那里需要放的是JSON.stringify(info)