问题描述:
前端发送异步请求加载ztree时,一直走error函数,并报405错误:Request method ‘GET’ not supported,无法从后台获取数据
原因:
检查发现,是jquery加载失败导致的,因此推测是jquery版本太低,不支持ajax新写法导致的,由于无法识别method属性,导致post方法使用失败,默认使用get方法请求后台,但控制器使用的接收类型是post,所以请求失败
$(document).ready(function(){
$.ajax({
url:"/system/role/getZtreeNodes.do",
data:{"roleId":$("#roleId").val()},
dataType:"json",
method:"post",
success:function (zNodes) {
initZtree(zNodes);
},
error:function () {
alert("服务器忙。。")
}
});
});
@PostMapping("/getZtreeNodes")
@ResponseBody
public List<Map<String,String>> getZtreeNodes(String roleId){
List<Map<String,String>> zNodes = new ArrayList<>();
List<Module> moduleList = moduleService.findAll();
//3. 根据角色id查询角色已经拥有的权限
List<Module> roleModuleList =
moduleService.findModuleByRoleId(roleId);
for (Module module : moduleList) {
//{ id:2, pId:0, name:"随意勾选 2", checked:true, open:true},
HashMap<String, String> map = new HashMap<>();
map.put("id",module.getId());
map.put("pId",module.getParentId());
map.put("name",module.getName());
if (roleModuleList.contains(module)){
map.put("checked","true");
};
map.put("open","true");
zNodes.add(map);
}
return zNodes;
}
解决办法:
将ajax里的method属性更改为type
$(document).ready(function(){
$.ajax({
url:"/system/role/getZtreeNodes.do",
data:{"roleId":$("#roleId").val()},
dataType:"json",
type:"post", //修改为type后,服务器即可以post方法发送请求
success:function (zNodes) {
initZtree(zNodes);
},
error:function () {
alert("服务器忙。。")
}
});
});
总结:
ztree默认使用的jquery版本为1.4.4,版本比较旧,不支持异步请求的新特性写法,使用时务必注意