重定向Ajax Jquery调用

时间:2010-05-28 06:36:15

标签: jquery ajax spring-mvc

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

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响应,但我不知道如何捕获响应并将用户重定向到登录 页。这有什么想法吗?感谢。

2 个答案:

答案 0 :(得分:49)

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

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

$(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...
            }
        }
//....

希望有所帮助。

我的答案受this thread的启发,如果您仍然遇到问题,不应该留下任何问题。

答案 1 :(得分:1)

对于ExpressJs路由器:

router.post('/login', async(req, res) => {
    return res.send({redirect: '/yoururl'});
})

客户端:

    success: function (response) {
        if (response.redirect) {
            window.location = response.redirect
        }
    },