2017-04-14 105 views
0

我有以下的功能,使一个请求:ModelAndView的不重定向,但给正确的响应

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请求: enter image description here

因此,在“预览”ta b的请求我有正确的页面,它应该重定向,但浏览器中没有重定向。该页面保持与postIngredient()函数初始调用的位置相同。那么如何重定向呢?

回答

1

您正在通过Javascript中的XMLHttpRequest对象发出ajax请求。这个请求通过重定向来回答,XMLHttpRequest对象遵循重定向,调用编辑,然后调用该结果(编辑页面的完整页面内容)被发送到您的xhr.onloadend()方法。浏览器窗口本身并没有涉及到,也不知道重定向是在内部发送的。

如果你想保留职位作为一个XHR请求,不切换到标准表单后,你可能会改变你的后处理方法只返回一个字符串:在JavaScript代码

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请求,获得来自resultdata结果字符串,并与一些重定向浏览器像

​​

@ResponseBody注释防止从春天在01解释返回的字符串作为视图名称和包装的字符串为您提供了在出现问题时返回错误代码的可能性。

+0

工程就像一个魅力。感谢您的解释和解决方案。 – Cristian

+0

不客气! –