简体   繁体   English

有没有办法可以在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

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 post将3个对象的列表作为字符串发送到我的控制器,如下所示。

JavaScript function for AJAX call: AJAX调用的JavaScript函数:

$.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;
    }

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. 在这里,我希望我的页面被重定向到审查(jsp)页面,但在我的情况下发生的是它仍然保留在同一页面但在网络的响应部分(在chrome dev工具中),我可以看到我的JSP页面以html格式,但页面未呈现。 Is there a way that I can render the review page? 有没有办法可以呈现评论页面?

You can't go to the page which you recived in the response to the POST request. 您无法转到在POST请求的响应中收到的页面。 But your can add success to ajax: 但是你可以为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);
    }

but now you also need make new controller with GET to return view for /content/review page 但现在您还需要使用GET创建新控制器以返回/content/review页面的视图

ps 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: ps另一个变体似乎是一个黑客,如果你仍然想要在不改变任何控制器的情况下渲染页面,你的成功必须是这样的:

success: function (response) {
        document.open();
        document.write(response);
        document.close();
    }

But this approach is not recommended. 但不推荐这种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM