Ajax发送请求传递多个参数时,我们可以通过表单序列化 $("form").serialize()
但是再加一个数组参数该传递就不行了。经过测试最终找到解决办法!
前端测试代码 test.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="<%=request.getContextPath() %>/static/jquery/1.9.1/jquery.min.js"></script>
<title>测试</title>
</head>
<body>
<form id="info">
<div>用户名:<input type="text" name="userName" id="userName"></div>
<div>密码:<input type="password" name="pwd" id="pwd"></div>
<div>超级管理员:<input type="checkbox" value="1" name="role" class="roles"> 管理员:<input type="checkbox" value="2" name="role" class="roles"></div>
<div><input type="button" value="提交" onclick="save()" ></div>
</form>
</body>
<script type="text/javascript">
function save(){
var userName = $("#userName").val();
var pwd = $("#pwd").val();
var roleList = getroleList(); //获取数组
$.ajax({
type: "post",
url: "<%=request.getContextPath() %>/user/addUser2",
dataType: "json",
//contentType:"application/json",//经测试,这里不能使用该传输类型
traditional: true,//这里设置为true,不然后台接收到的参数会带上[],导致数据无法正常接收
data:{"userName":userName,"pwd":pwd,"roleList":roleList},
success: function(json){
alert("成功!");
},
error: function(json){
alert("操作出错");
return false;
}
});
}
function getroleList(){
var roleList=[];
var roles = $(".roles")
var i =0 ;
for(k in roles){
if(roles[k].checked){
if(i<=roles.length){
var role=roles[k].value;
roleList.push(role);
i++;
}
}
}
return roleList ;
}
</script>
</html>
Controller控制层代码
package com.liuchao.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.liuchao.projo.JResult;
import com.liuchao.service.UserRoleService;
@Controller
@RequestMapping("/user")
public class UserRoleController {
@Autowired
private UserRoleService userRoleService;
@RequestMapping("/addUser2")
@ResponseBody
public JResult addUser2(String userName,String pwd,String [] roleList) {//此处必须使用数组接收,名称和前端Ajax的参数名一致。
System.out.println(userName+pwd+roleList.toString());
return userRoleService.addUser2(userName,pwd,roleList);
}
}