我如何重定向到其他页面的JSON请求类型? [英] how do i redirect to any other page for json request type?

查看:169
本文介绍了我如何重定向到其他页面的JSON请求类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序将用户重定向到登录页面,只要没有会议。但是对于Ajax请求重定向这是不会发生。

my application redirects the user to the login page whenever there is no session. But for Ajax request this redirecting is not happening.

我需要处理这种重定向问题在应用程序的所有Ajax调用。

I need to handle this redirection issue for all ajax calls in the application.

推荐答案

我是对的Zend / PHP项目做类似的事情。不幸的是,我不熟悉Java并有我可以建议只有基本的方向。

I were doing similar thing on Zend/PHP project. Unfortunately, I'm not familiar with Java and there I can suggest only basic direction.

在默认情况下,XMLHtt prequest执行重定向。所以,如果你的AJAX请求过程中进行重定向,XMLHtt prequest会不会让你知道,重定向发生在所有的执行。至少我发现没有办法赶上这样的情况,不知怎么处理它。正因为如此,在服务器端我重写重定向方法。假设你可以做这样的事情在Java中了。一旦请求来自阿贾克斯(你可以添加一些特定的标题,您的Ajax请求,并检查它在服务器上),你可以返回从位置头不同的标题。例如,新位置,并做没有实际的重定向。只要停止执行请求。

By default, XMLHttpRequest execute redirects. So if you do a redirect during ajax request, XMLHttpRequest will execute it without letting you know that redirect happened at all. At least I found no way to catch such situation and handle it somehow. Because of that, on server side I override a redirect method. Suppose you can do something like that in Java too. Once request came from ajax (you can add a some specific header to your ajax request and check it on server) you can return a header different from Location header. For instance, New-Location, and do no actual redirect. Just stop request execution.

在客户端,您可以使用 jQuery.ajaxSetup 配置全局处理程序,所有的Ajax请求立刻。 这里是你可以添加一个头的所有请求与 .ajaxSetup

On client side you can use jQuery.ajaxSetup to configure global handler for all ajax requests at once. Here is how you can add a header to all requests with .ajaxSetup:

$.ajaxSetup({
    headers: {
        XHTTPRequest: 'true'
    }
});

此外,你可以设置一个全球性的的ajaxSuccess 和的 ajaxError 处理程序。他们将一个单独的Ajax请求的任何成功/错误处理程序之前执行。在全局AJAX的成功,你可以从传递的第三个参数的回调函数,做一个重定向 XHR 对象的标题:

Additionally you can set a global ajaxSuccess and ajaxError handlers. They will be executed before any success/error handler of a separate ajax request. In global ajax success you can take a header from xhr object passed as a third parameter to callback function and do a redirect:

var newLocation = xhr.getResponseHeader("New-Location");
if(newLocation)
     document.location = newLocation;

基本上,你可以返回,而不是头特殊对象还是找传递一个新的位置,你的的ajaxSuccess 回调一些其他的方式。

Basically, you can return special object instead of header or find some other way to pass a new location to your ajaxSuccess callback.

这篇关于我如何重定向到其他页面的JSON请求类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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