在springmvc中的ajax发布调用之后,有什么方法可以将我的页面(jsp)重定向到另一个页面(jsp) [英] Is there a way that I can redirect my page (jsp) to another page (jsp) after an ajax post call in springmvc
问题描述
基本上我的情况是我尝试通过使用ajax post将3个对象的列表作为字符串发送到我的控制器,如下所示.
Basically my scenario is I am trying to send a list of 3 objects as a string to my controller by using ajax post as shown below.
用于AJAX调用的JavaScript函数:
JavaScript function for AJAX call:
$.ajax({
type: 'POST',
dataType: 'json',
url: "ajaxEditFormUpdate",
data: JSON.stringify(newData),
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
}
});
MyController:
MyController:
@RequestMapping(value = "ajaxEditFormUpdate", method = RequestMethod.POST)
@ResponseBody
public ModelAndView handleResponse(@RequestBody String records) {
System.out.println(records);
String viewName = "content/review";
ModelAndView mav = new ModelAndView();
mav.setViewName(viewName);
return mav;
}
在这里,我希望将页面重定向到review(jsp)页面,但是在我的情况下,它仍然保留在同一页面中,但是在网络的响应部分(在chrome dev工具中),我可以看到我的JSP页面为html格式,但该页面未呈现.有什么方法可以渲染评论页面?
Here I want my page to be redirected to review(jsp) page, but whats happening in my case is it still retains in the same page but in the response section of the network(in chrome dev tools), I can see my JSP page in html format, but the page is not being rendered. Is there a way that I can render the review page?
推荐答案
您无法转到响应POST请求而返回的页面. 但是您可以在Ajax中添加成功:
You can't go to the page which you recived in the response to the POST request. But your can add success to ajax:
$.ajax({
type: 'POST',
dataType: 'json',
url: "ajaxEditFormUpdate",
data: JSON.stringify(newData),
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function (response) {
window.location.href = '/content/review';
}
});
您的控制器现在将如下所示:
You controller now will be looking like this:
@RequestMapping(value = "ajaxEditFormUpdate", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Void> handleResponse(@RequestBody String records) {
System.out.println(records);
return new ResponseEntity<>(HttpStatus.OK);
}
但是现在您还需要使用GET创建新的控制器以返回/content/review
页面的视图
but now you also need make new controller with GET to return view for /content/review
page
p.s..如果您仍然希望在不更改任何控制器的情况下呈现页面,则另一个变种似乎是一种破解,您的成功必定是这样的:
p.s. Another variant seems to be a hack if you still want to render page without changing any controllers, your success must will be like this:
success: function (response) {
document.open();
document.write(response);
document.close();
}
但是不推荐这种方法.
这篇关于在springmvc中的ajax发布调用之后,有什么方法可以将我的页面(jsp)重定向到另一个页面(jsp)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!