记录 Springboot + ajax 导致的页面不跳转的问题
作者: 时间:2023-05-30阅读数:人阅读
记录 Springboot + ajax 导致的页面不跳转的问题
问题描述
ajax 去调用后端接口:
var params = {
"r_id": r_id,
"r_name": r_name,
"r_state": r_state,
"menus": menus
}
$.ajax({
type: "POST",
url: "/role/update",
data: params,
success: function (r) {
console.log(r)
window.location.href = "/role/list";
},
error:function(result) {
alert("error");
}
})
被调用的后端接口如下:
@PostMapping("/update")
public String update(RoleSaveReq req) {
int save = roleService.save(req);
LOG.info("更新完成,更新条数为{}",save);
return "redirect:/role/list";
}
上面的后端接口尝试调用的另一个后端接口:
这个接口是用来查询数据,并跳转到展示页面的
@GetMapping("/list")
public String list(RoleQueryReq req, Model model) {
LOG.info("尝试访问接口{}","/role/list");
if (req==null) {
req = new RoleQueryReq();
}
LOG.info("传入的参数信息为:{}",req);
PageResp list = roleService.list(req);
CommonResp commonResp = new CommonResp();
commonResp.setContent(list);
model.addAttribute("resp",commonResp);
model.addAttribute("searchRole",req.getR_name());
LOG.info("model中的数据为:{}",model.getAttribute("resp"));
return "Role/index";
}
一开始的想法是,ajax 请求结束后,由后端接口,在调用另一个后端接口,最后跳转到展示页面的
但是,页面就是死活不跳转,折腾了一下午,才找到问题所在
当使用 ajax 后,SpringMVC 返回的字符串,就会返回整个页面,传到 ajax 的回调函数中,而不是进行页面跳转!!!
解决方法
被 ajax 调用的后端接口,必须加上 @ResponseBody 注解:
这样,返回到 ajax 回调函数中的数据,就是一个字符串
然后在 ajax 的回调函数中,再去访问需要的后端接口:
window.location.href = "/role/list";
本站所有文章、数据、图片均来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:licqi@yunshuaiweb.com