解决ajax提交复选框数据和表单数据后台接收失败的问题代码如下
<tr>
<td>选择联系人</td>
<td>
<ul>
<!--thymeleaf遍历用户信息-->
<li th:each="user,userStat : ${list}">
<label th:for="${userStat.index}" th:text="${userStat.index}+1"></label>
<input type="checkbox" th:value="${user.id}" th:id="${userStat.index}" th:text="${user.userName}">
</li>
</ul>
</td>
</tr>
//定义数组,遍历选择的复选框的值,传入数组
var userIds = [];
$("input[type='checkbox']:checked").each(function () {
var _this = $(this);
userIds.push(_this.val());
});
//其他input值
var title = $("#title").val();
//ajax提交
$.ajax({
url:"/websocketserver/haha/add",
data:{
'title': title,
'userIds':userIds
},
method:'post',
dataType:'json',
traditional:true,//要加这个参数,不然后台无法接收
success:function (data) {
console.log(data);
}
})
后台 springboot接收参数
@RequestMapping("/add")
@ResponseBody
public ResultBean add(String title,String[] userIds) throws IOException {
MessageInfo messageInfo = new MessageInfo();
messageInfo.setContent(content);
messageInfo.setContent("无论走到哪,都要记住过去都是假的," +
"回忆是一条没有归途的路,以往的一切春天都无法复原," +
"即使最狂热最坚贞的爱情,归根结底也不过是一种瞬息即逝的现实," +
"唯有孤独永恒。");
messageInfo.setSendTime(new Date());
messageInfo.setTitle(title);
boolean i = messageInfoService.save(messageInfo);
if (i){
for (String userId : userIds){
StatusInfo statusInfo = new StatusInfo();
statusInfo.setUserId(Integer.parseInt(userId));
statusInfo.setTitleMessage(messageInfo.getTitle());
statusInfo.setStatus(0);
statusInfo.setMessageId(messageInfo.getId());
statusInfo.setSendTime(new Date());
statusInfoService.save(statusInfo);
}
}else {
log.error("消息添加失败");
}
//推送消息
for (String userId : userIds){
QueryWrapper<StatusInfo> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("user_id",userId);
queryWrapper.eq("status",0);
List<StatusInfo> statusInfos = statusInfoService.list(queryWrapper);
//连接进了websocket
redisUtils.set(userId,JSON.toJSONString(statusInfos));
WebSocketServer.sendInfo(JSON.toJSONString(statusInfos),userId);
}
return new ResultBean(200,"消息发送成功");
}