Redirect on Ajax Jquery Call

前端 未结 2 875
长情又很酷
长情又很酷 2020-12-01 06:28

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 redirect

相关标签:
2条回答
  • 2020-12-01 07:10

    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.

    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:

    $(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(!):

    //....
            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.

    0 讨论(0)
  • 2020-12-01 07:26

    For ExpressJs router:

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

    Client-side:

        success: function (response) {
            if (response.redirect) {
                window.location = response.redirect
            }
        },
    
    0 讨论(0)
提交回复
热议问题