我正在使用 Spring MVC 构建一个项目。我想将一个 JSON 对象从当前页面传输到下一页。我所做的是创建一个 Controller ,我通过 POST AJAX 调用将对象发送到该 Controller 。然后, Controller 为存储为 jsp 的下一页创建一个 ModelAndView 对象,将该对象添加为所述 ModelAndView 的属性之一,然后返回它。现在我需要重定向到作为 ModelAndView 返回的页面。相关代码如下:
Controller :
public ModelAndView nextPageController(@RequestBody String passedJsonString) {
ModelAndView nextPage = new ModelAndView("/nextPage.jsp");
nextPage.addObject("passedJsonString", passedJsonString);
return nextPage;
}
AJAX 调用:
controllerUrl = "/controller/path";
$.ajax({
type : "POST",
headers : {
'Accept' : 'application/json',
'Content-Type' : 'application/json'
},
url : controllerUrl,
data : JSON.stringify(jsonDataToBePassed),
success : function(dataString) {
console.log(dataString);
}
});
AJAX 调用成功执行,并按预期返回 ModelAndView 对象。现在我需要渲染下一个页面,并且 Controller 中添加的属性完好无损。我意识到我正在做的事情可能是错误的,并且可能有更好的方法来实现这一点,所以任何关于如何做到这一点的指导都可能会受到赞赏。
最佳答案
当您对 Controller 进行 ajax 调用时,它需要一些结果,您可以根据该结果继续操作。
在您的情况下,响应已在 Controller 成功完成后返回到 ajax 函数。
如果你想发送到另一个页面然后在 Controller 中编写一个方法并在该 Controller 方法中返回页面(/nextPage.jsp)。
在你的代码下面。
success : function(dataString) {
window.location.href = "/path/of/controllerMethod"; //redirect to controller method which returns the jsp page
}
并创建如下方法:
@RequestMapping(value="/path/of/controllerMethod")
public ModelAndView returnJspPageControllerMethod() {
ModelAndView nextPage = new ModelAndView("/nextPage.jsp");
return nextPage;
}
关于javascript - Spring MVC : Render page from ModelAndView in AJAX call,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50899422/