How to prevent ajax requests to follow redirects using jQuery

前端 未结 9 638
梦如初夏
梦如初夏 2020-11-27 14:37

I use the jQuery ajax functions to access a web service, but the server, instead of returning a response with a status code describing a problem, the request is redirected t

9条回答
  •  野性不改
    2020-11-27 15:25

    I don't believe it is possible. The underlying library (XHR) makes the new request transparently. That being said, what I have done in these situations (usually a session-timeout type of deal that takes me to a login page) is send back a custom response header. I also have setup a global ajax handler that checks for the presence of that header, and responds appropriately when present (for example, redirecting the whole page to the login screen).

    In case you're interested, here's the jQuery code I have to watch for that custom header:

    /* redirects main window when AJAX request indicates that the session has expired on the backend. */
    function checkSession(event, xhr, ajaxOptions)
    {
        if (xhr.readyState == 4)
        {
            if(xhr.getResponseHeader("Login-Screen") != null && xhr.getResponseHeader("Login-Screen").length)
            {
                window.location.href='sessionExpired.html'; //whatever
            }
        }
    }
    
    $(document).ajaxComplete(checkSession)
    

提交回复
热议问题