简体   繁体   English

重定向 Ajax Jquery 调用

[英]Redirect on Ajax Jquery Call

I am newbie to ajax here and I know somebody would have encountered this problem already.我是 ajax 的新手,我知道有人已经遇到过这个问题。 I have a legacy app built on Spring MVC, it has a interceptor(filter) that redirects the user to the login page whenever there is no session.我有一个基于 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;
 }
}

For non-xmlhttp request, this works fine.. but when I try to use ajax in my application, everything gets weird, it is not able to redirect to the login page correctly.对于非 xmlhttp 请求,这工作正常..但是当我尝试在我的应用程序中使用 ajax 时,一切都变得奇怪,它无法正确重定向到登录页面。 As check the value of the作为检查的值

xhr.status = 200 textStatus = parseError errorThrown = "Invalid JSON -Markup of my HTML Login Page- 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);
             }

        });
});

I checked on my firebug that there is a 302 HTTP response but I am not sure how to catch the response and redirect the user to the login page.我检查了我的萤火虫是否有 302 HTTP 响应,但我不确定如何捕获响应并将用户重定向到登录页面。 Any idea here?这里有什么想法吗? Thanks.谢谢。

JQuery is looking for a json type result, but because the redirect is processed automatically, it will receive the generated html source of your login.htm page. JQuery 正在寻找一个json类型的结果,但是因为重定向是自动处理的,它会收到你的login.htm页面生成的 html 源代码

One idea is to let the the browser know that it should redirect by adding a redirect variable to to the resulting object and checking for it in JQuery:一种想法是让浏览器知道它应该通过向结果对象添加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); 
         } 

    }); 
}); 

You could also add a Header Variable to your response and let your browser decide where to redirect.您还可以在响应中添加一个 Header Variable,让您的浏览器决定重定向的位置。 In Java, instead of redirecting, do response.setHeader("REQUIRES_AUTH", "1") and in JQuery you do on success(!):在 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...
            }
        }
//....

Hope that helps.希望有帮助。

My answer is heavily inspired by this thread which shouldn't left any questions in case you still have some problems.我的回答深受此线程的启发,如果您仍有问题,不应留下任何问题。

For ExpressJs router:对于 ExpressJs 路由器:

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

Client-side:客户端:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM