【问题标题】:Is there a way that I can redirect my page (jsp) to another page (jsp) after an ajax post call in springmvc有没有一种方法可以在springmvc中的ajax post调用之后将我的页面(jsp)重定向到另一个页面(jsp)
【发布时间】:2017-07-21 10:41:22
【问题描述】:

基本上我的场景是我试图通过使用 ajax post 将 3 个对象的列表作为字符串发送到我的控制器,如下所示。

用于 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");  
    }
});

我的控制器:

@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;
    }

在这里我希望我的页面被重定向到审查(jsp)页面,但在我的情况下发生的事情是它仍然保留在同一页面中,但在网络的响应部分(在 chrome 开发工具中),我可以看到我的 html 格式的 JSP 页面,但该页面没有被呈现。有没有办法可以呈现评论页面?

【问题讨论】:

    标签: javascript jquery ajax jsp spring-mvc


    【解决方案1】:

    您无法访问您在响应 POST 请求时收到的页面。 但是您可以将 success 添加到 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';
    }
    });
    

    你的控制器现在看起来像这样:

    @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 页面的视图

    p.s. 如果您仍然想在不更改任何控制器的情况下呈现页面,那么另一个变体似乎是一种 hack,您的成功必须是这样的:

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

    但不推荐这种方式。

    【讨论】:

    • 您更喜欢哪种变体:普通还是破解?
    • 普通的,通过添加一个额外的控制器来获取评论页面
    猜你喜欢
    • 2014-06-24
    • 1970-01-01
    • 2013-02-18
    • 2018-03-15
    • 1970-01-01
    • 2012-01-30
    • 2013-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多