重定向 Ajax Jquery 调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2927044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:33:29  来源:igfitidea点击:

Redirect on Ajax Jquery Call

jqueryajaxspring-mvc

提问by Mark Estrada

I am newbie to ajax here and I know somebody would have encountered this problem already. 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.

我是 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;
 }
}

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. As check the value of the

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

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. Any idea here? Thanks.

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

回答by thmshd

JQuery is looking for a jsontype result, but because the redirect is processed automatically, it will receive the generated html sourceof your login.htmpage.

JQuery 正在寻找一个json类型的结果,但是因为重定向是自动处理的,所以它会收到你页面生成的 html 源代码login.htm

One idea is to let the the browser know that it should redirect by adding a redirectvariable to to the resulting object and checking for it in JQuery:

一个想法是让浏览器知道它应该通过向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); 
         } 

    }); 
}); 

You could also add a Header Variable to your response and let your browser decide where to redirect. In Java, instead of redirecting, do response.setHeader("REQUIRES_AUTH", "1")and in JQuery you do on success(!):

您还可以在响应中添加一个 Header Variable,让您的浏览器决定重定向的位置。在 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 threadwhich shouldn't left any questions in case you still have some problems.

我的回答深受此线程的启发,如果您仍有问题,不应留下任何问题。

回答by Hammad Khokhar

For NodeJS router:

对于 NodeJS 路由器:

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

Client-side:

客户端:

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