【问题标题】:ModelAndView does not redirect, but give correct responseModelAndView 不重定向,但给出正确的响应
【发布时间】:2017-04-14 21:47:05
【问题描述】:

我有以下发出请求的函数:

function postIngredient(action, options) {
    var xhr = new XMLHttpRequest();
    xhr.open(options.method, action, true);
    xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
    xhr.setRequestHeader(options.security.header, options.security.token);

    // send the collected data as JSON
    xhr.send(JSON.stringify(options.params));

    xhr.onloadend = function () {
        // done
    };
}

该函数在服务器上触发一个方法,该方法基本上返回一个 ModelAndView 对象:

...   
ModelAndView mav = new ModelAndView("redirect:/recipies/edit?id=1");  
....  
return mav;  

发布请求成功完成后,将完成以下 GET 请求:

所以在请求的“预览”选项卡中,我有正确的页面应该重定向,但浏览器中没有重定向。该页面与最初调用 postIngredient() 函数的位置相同。那么如何进行重定向呢?

【问题讨论】:

    标签: javascript java spring redirect modelandview


    【解决方案1】:

    您正在通过 Javascript 的 XMLHttpRequest 对象发出 ajax 请求。使用重定向响应此请求,并且 XMLHttpRequest 对象跟随重定向,调用编辑,然后将结果(编辑页面的完整页面内容)发送到您的 xhr.onloadend() 方法。浏览器窗口本身不参与其中,也不知道重定向是在内部发送的。

    如果您想将帖子保留为 xhr 请求并且不切换到标准表单帖子,您可以更改您的后处理方法以仅返回一个字符串:

    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    @ResponseBody
    public ResponseEntity<String> myPostProcessingIngredientsMethod(..put args here...) {
      ... do something ...
      return new ResponseEntity<>("/recipies/edit?id=1", HttpStatus.OK));
    }
    

    然后在您执行 xhr 请求的 Javascript 代码中,从 resultdata 中获取结果字符串并使用类似的内容重定向您的浏览器

    window.location.href = dataFromResult;
    

    @ResponseBody 注释可防止 Spring 将返回的字符串解释为视图名称并将字符串包装在 ResponseEntity 中,这样您就可以在出现问题时返回错误代码。

    【讨论】:

    • 像魅力一样工作。感谢您的解释和解决方案。
    猜你喜欢
    • 2021-03-28
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 2012-11-19
    • 2011-09-27
    • 2023-03-03
    • 2015-09-15
    • 1970-01-01
    相关资源
    最近更新 更多