我使用$.post()使用Ajax调用servlet,然后使用生成的HTML片段替换用户当前页面中的div元素。但是,如果会话超时,服务器将发送重定向指令,将用户发送到登录页面。在本例中,jQuery用登录页面的内容替换div元素,迫使用户的眼睛看到一个罕见的场景。
如何使用jQuery1.2.6管理Ajax调用的重定向指令?
我使用$.post()使用Ajax调用servlet,然后使用生成的HTML片段替换用户当前页面中的div元素。但是,如果会话超时,服务器将发送重定向指令,将用户发送到登录页面。在本例中,jQuery用登录页面的内容替换div元素,迫使用户的眼睛看到一个罕见的场景。
如何使用jQuery1.2.6管理Ajax调用的重定向指令?
当前回答
Try
$(document).ready(function () {
if ($("#site").length > 0) {
window.location = "<%= Url.Content("~") %>" + "Login/LogOn";
}
});
把它放在登录页面上。如果它被加载到主页上的一个div中,它将重定向到登录页面。“#site”是位于除登录页面之外的所有页面上的div的id。
其他回答
使用低级$.ajax()调用:
$.ajax({
url: "/yourservlet",
data: { },
complete: function(xmlHttp) {
// xmlHttp is a XMLHttpRquest object
alert(xmlHttp.status);
}
});
尝试此操作进行重定向:
if (xmlHttp.code != 200) {
top.location.href = '/some/other/page';
}
在servlet中,您应该将response.setStatus(response.SC_MOVED_PERMANENTLY);要发送重定向所需的“301”xmlHttp状态。。。
在$.ajax函数中,不应使用.toString()函数。。。,只是
如果(xmlHttp.status==301){top.location.href='xxxx.jsp';}
问题是它不是很灵活,你无法决定要重定向到哪里。。
通过servlet重定向应该是最好的方法。但我仍然找不到正确的方法。
最后,我通过添加自定义HTTP头来解决这个问题。就在服务器端响应每个请求之前,我将当前请求的url添加到响应的头部。
我在服务器上的应用程序类型是Asp.NetMVC,这是一个很好的地方。在Global.asax中,我实现了application_EndRequest事件,因此:
public class MvcApplication : System.Web.HttpApplication
{
// ...
// ...
protected void Application_EndRequest(object sender, EventArgs e)
{
var app = (HttpApplication)sender;
app.Context.Response.Headers.Add("CurrentUrl",app.Context. Request.CurrentExecutionFilePath);
}
}
它非常适合我!现在,在JQuery$.post的每个响应中,我都有请求的url和其他响应头,这些响应头是post方法的结果,状态为302、303。
另一个重要的是,不需要在服务器端或客户端修改代码。
下一个是能够访问动作后的其他信息,例如错误、消息和。。。,以这种方式。
我发布了这个,也许可以帮助某人:)
我这样解决了这个问题:
添加一个中间件来处理响应,如果是对ajax请求的重定向,则使用重定向url将响应更改为正常响应。
class AjaxRedirect(object):
def process_response(self, request, response):
if request.is_ajax():
if type(response) == HttpResponseRedirect:
r = HttpResponse(json.dumps({'redirect': response['Location']}))
return r
return response
然后在ajaxComplete中,如果响应包含重定向,则它必须是重定向,因此请更改浏览器的位置。
$('body').ajaxComplete(function (e, xhr, settings) {
if (xhr.status == 200) {
var redirect = null;
try {
redirect = $.parseJSON(xhr.responseText).redirect;
if (redirect) {
window.location.href = redirect.replace(/\?.*$/, "?next=" + window.location.pathname);
}
} catch (e) {
return;
}
}
}
<script>
function showValues() {
var str = $("form").serialize();
$.post('loginUser.html',
str,
function(responseText, responseStatus, responseXML){
if(responseStatus=="success"){
window.location= "adminIndex.html";
}
});
}
</script>