前端js:
$.ajax({
type: "get",//请求类型
url: path + "/jsp/user.do",//请求的url
data: {method: "rolelist"},//请求参数
dataType: "json",//ajax接口(请求url)返回的数据类型
contentType:"application/json;charset=utf-8",
async:false,
success: function (data) {//data:返回数据(json对象)
alert(data);
if (data != null) {
userRole.html("");
var options = "<option value=\"0\">请选择</option>";
for (var i = 0; i < data.length; i++) {
alert(data[i].id);
alert(data[i].roleName);
options += "<option value=\"" + data[i].id + "\">" + data[i].roleName + "</option>";
}
userRole.html(options);
}
},
error: function (data) {//当访问时候,404,500 等非200的错误状态码
validateTip(userRole.next(), {"color": "red"}, imgNo + " 获取用户角色列表error", false);
}
})
后端servlet:
public void rolelist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
System.out.println("rolelist");
RoleServiceImpl roleService = new RoleServiceImpl();
List<Role> roleList = roleService.getRoleList();
req.setAttribute("RoleList",roleList);
Map<String, String> roleMap = new HashMap<String, String>();
for (Role role : roleList) {
roleMap.put(String.valueOf(role.getId()),role.getRoleName());
}
resp.setContentType("application/json");
PrintWriter writer = resp.getWriter();
writer.write(JSONArray.toJSONString(roleMap));
writer.flush();//刷新
writer.close();//关闭
System.out.println(JSONArray.toJSONString(roleMap));//这能输出预想参数
System.out.println(writer);
}