如何防止jQuery ajax在帖子后重定向?

时间:2022-12-01 22:39:27

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.

我有一个链接调度Ajax POST来执行操作。如果用户尚未登录,则action方法返回302重定向到登录页面。如果发生这种情况,我想捕获重定向,以便我可以在灯箱中显示登录表单。

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.

但是,似乎jQuery遵循重定向而不返回控制或调用回调函数。在下面的代码中,从不调用302重定向的警报,并且在调用dataFiler函数时,数据是登录页面的内容。

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

如何看到页面已发送302重定向,并分支到不同的操作?

 $.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 个解决方案

#1


12  

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.

这不是jQuery的限制,而是JavaScript本身;没有办法在JavaScript中检测AJAX请求中的重定向;浏览器XHR对象自动神奇地按照规范无形地遵循重定向。

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.

理想的选择是在服务器代码中添加一个catch以检测AJAX请求(“HTTP_X_REQUESTED_WITH”标头),并返回一个特殊响应来检测JavaScript中的匿名用户,并进行适当处理。

#1


12  

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.

这不是jQuery的限制,而是JavaScript本身;没有办法在JavaScript中检测AJAX请求中的重定向;浏览器XHR对象自动神奇地按照规范无形地遵循重定向。

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.

理想的选择是在服务器代码中添加一个catch以检测AJAX请求(“HTTP_X_REQUESTED_WITH”标头),并返回一个特殊响应来检测JavaScript中的匿名用户,并进行适当处理。