Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

http - How to prevent jQuery ajax from following a redirect after a post?

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; }
        });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...