重定向Ajax Jquery调用

我是ajax的新手,我知道有人会遇到这个问题。 我有一个基于Spring MVC构建的遗留应用程序,它有一个拦截器(filter),可以在没有会话时将用户重定向到登录页面。

public class SessionCheckerInterceptor extends HandlerInterceptorAdapter { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(); // check if userInfo exist in session User user = (User) session.getAttribute("user"); if (user == null) { response.sendRedirect("login.htm"); return false; } return true; } } 

对于非xmlhttp请求,这工作正常..但是当我尝试在我的应用程序中使用ajax时,一切都变得奇怪,它无法正确地重定向到登录页面。 检查的价值

xhr.status = 200 textStatus = parseError errorThrown =“我的HTML登录页面无效的JSON -Markup-

 $(document).ready(function(){ jQuery.ajax({ type: "GET", url: "populateData.htm", dataType:"json", data:"userId=SampleUser", success:function(response){ //code here }, error: function(xhr, textStatus, errorThrown) { alert('Error! Status = ' + xhr.status); } }); }); 

我检查了我的firebug有一个302 HTTP响应,但我不知道如何捕获响应并将用户重定向到登录页面。 这有什么想法? 谢谢。

JQuery正在寻找json类型的结果,但由于重定向是自动处理的,它将接收login.htm页面生成的html源代码

一个想法是让浏览器知道它应该通过向结果对象添加redirect变量并在JQuery中检查它来redirect

 $(document).ready(function(){ jQuery.ajax({ type: "GET", url: "populateData.htm", dataType:"json", data:"userId=SampleUser", success:function(response){ if (response.redirect) { window.location.href = response.redirect; } else { // Process the expected results... } }, error: function(xhr, textStatus, errorThrown) { alert('Error! Status = ' + xhr.status); } }); }); 

您还可以在响应中添加标头变量,并让浏览器决定重定向的位置。 在Java中,不是重定向,而是执行response.setHeader("REQUIRES_AUTH", "1")并在JQuery中成功执行(!):

 //.... success:function(response){ if (response.getResponseHeader('REQUIRES_AUTH') === '1'){ window.location.href = 'login.htm'; } else { // Process the expected results... } } //.... 

希望有所帮助。

我的回答很大程度上受到这个主题的启发,如果你还有一些问题,不应该留下任何问题。