Javascript ModelAndView不重定向,但给出正确的响应
我具有以下发出请求的功能:Javascript ModelAndView不重定向,但给出正确的响应,javascript,java,spring,redirect,modelandview,Javascript,Java,Spring,Redirect,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.sec
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;
post请求成功完成后,将完成以下GET请求:
因此,在请求的“预览”选项卡中,我有一个正确的页面,该页面应该重定向,但浏览器中没有重定向。该页面与最初调用PostingCredit()函数的位置相同。那么如何进行重定向呢?您正在通过Javascript中的XMLHttpRequest对象发出ajax请求。此请求通过重定向得到响应,XMLHttpRequest对象跟随重定向,调用编辑,然后将结果(编辑页面的完整页面内容)发送到xhr.onloadend()方法。浏览器窗口本身不涉及这一点,也不知道重定向是在内部发送的 如果希望将post保留为xhr请求,并且不切换到标准表单post,则可以更改post处理方法,以仅返回字符串:
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));
}
@ResponseBody
注释防止Spring将返回的字符串解释为视图名称,并将字符串包装在ResponseEntity
中,这样,如果出现问题,您就可以返回错误或代码。的工作非常有效。感谢您的解释和解决方案。
window.location.href = dataFromResult;