Java后台向Ajax传递List类型的JSON参数
问题:
Ajax中data接收来自后台的JSON数据,然后遍历显示。之前遇到的data数据通过键值对来访问,但是这次的是Role类型的List列表。
解决:
直接JSONArray.toJSonString(roleList),将roleList转成Json格式传输到前端即可。
展示效果
Ajax代码
$.ajax({
type:"get",//请求类型
url:path+"/user/getrolelist",//请求的url
data:{method:"getrolelist"},//请求参数
dataType:"json",//ajax接口(请求url)返回的数据类型
success:function(data){//data:返回数据(json对象)
if(data != null){
userRole.html("");
var options = "";
for(var i = 0; i < data.length; i++){
//alert(data[i].id);
//alert(data[i].roleName);
options += "";
}
userRole.html(options);
}
},
error:function(data){//当访问时候,404,500 等非200的错误状态码
validateTip(userRole.next(),{"color":"red"},imgNo+" 获取用户角色列表error",false);
}
});
java后台
// 查询角色列表
public void getrolelist(HttpServletRequest req, HttpServletResponse resp){
// 添加角色列表
RoleServiceImpl roleService = new RoleServiceImpl();
List roleList = roleService.getRoleList();
resp.setContentType("application/json");
PrintWriter writer = null;
try {
writer = resp.getWriter();
} catch (IOException e) {
e.printStackTrace();
}
writer.write(JSONArray.toJSONString(roleList));
writer.flush();
writer.close();
}