如何防止jQuery ajax在帖子后重定向? [英] How to prevent jQuery ajax from following a redirect after a post?

查看:205
本文介绍了如何防止jQuery ajax在帖子后重定向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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.

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

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; }
        });


推荐答案

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

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.

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

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.

这篇关于如何防止jQuery ajax在帖子后重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆