How to prevent jQuery ajax from following a redire

2020-02-05 06:57发布

问题:

I have a link which dispatches an Ajax POST to perform an action. If the user is not yet signed in, the action method returns a 302 redirect to the login page. If this happens, I want to catch the redirect, so that I can display the login form in a lightbox.

However, it seems that jQuery follows the redirect without returning control or calling a callback function. In the code below, the alert of 302 redirect is never called, and by the time the dataFiler function is called, the data is the content of the login page.

How can I see that the page has sent a 302 redirect, and branch to a different action?

 $.ajax(url,
        {
            data: postArguments,
            type : "POST",
            success: function (data) { alert(' success function'); },
            statusCode:
            {
                302: function () { alert(' received redirect 302'); },
                301: function () { alert(' received redirect 301'); }
            },
            dataFilter: function (data, type) { alert('got data ' + data); return data; }
        });

回答1:

This is not a limitation with jQuery but with JavaScript itself; there is no way to detect a redirect in an AJAX request in JavaScript; the browser XHR objects auto-magically and invisibly follow redirects as per the spec.

The ideal option would be to add a catch in your server code to detect an AJAX request ("HTTP_X_REQUESTED_WITH" header), and return a special response to detect an anonymous user in your JavaScript, and handle appropriately.