小编典典

重定向到Ajax jQuery调用

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 =“无效的JSON-我的HTML登录页的标记-

$(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);
             }

        });
});

我检查了萤火虫是否存在302 HTTP响应,但不确定如何捕获响应并将用户重定向到登录页面。有什么想法吗?谢谢。


阅读 545

收藏
2020-06-01

共1个答案

小编典典

jQuery是寻找一个 JSON 类型的搜索结果,但因为重定向自动处理,它将接收 生成的html源 你的login.htm页面。

一种想法是通过将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...
            }
        }
//....

希望能有所帮助。

2020-06-01