如何在 jQuery Ajax 调用后管理重定向请求 [英] How to manage a redirect request after a jQuery Ajax call

查看:43
本文介绍了如何在 jQuery Ajax 调用后管理重定向请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 $.post() 使用 Ajax 调用 servlet,然后使用生成的 HTML 片段替换用户当前页面中的 div 元素.但是,如果会话超时,服务器会发送重定向指令将用户发送到登录页面.在这种情况下,jQuery 正在用登录页面的内容替换 div 元素,迫使用户的眼睛确实看到了一个罕见的场景.

I'm using $.post() to call a servlet using Ajax and then using the resulting HTML fragment to replace a div element in the user's current page. However, if the session times out, the server sends a redirect directive to send the user to the login page. In this case, jQuery is replacing the div element with the contents of the login page, forcing the user's eyes to witness a rare scene indeed.

如何使用 jQuery 1.2.6 从 Ajax 调用中管理重定向指令?

How can I manage a redirect directive from an Ajax call with jQuery 1.2.6?

推荐答案

最终实现的解决方案是对 Ajax 调用的回调函数使用包装器,并在此包装器中检查特定元素的存在返回的 HTML 块.如果找到该元素,则包装器执行重定向.如果没有,包装器将调用转发到实际的回调函数.

The solution that was eventually implemented was to use a wrapper for the callback function of the Ajax call and in this wrapper check for the existence of a specific element on the returned HTML chunk. If the element was found then the wrapper executed a redirection. If not, the wrapper forwarded the call to the actual callback function.

例如,我们的包装函数是这样的:

For example, our wrapper function was something like:

function cbWrapper(data, funct){
    if($("#myForm", data).length > 0)
        top.location.href="login.htm";//redirection
    else
        funct(data);
}

然后,在进行 Ajax 调用时,我们使用了类似的东西:

Then, when making the Ajax call we used something like:

$.post("myAjaxHandler", 
       {
        param1: foo,
        param2: bar
       },
       function(data){
           cbWrapper(data, myActualCB);
       }, 
       "html"
);

这对我们有用,因为所有 Ajax 调用总是在 DIV 元素中返回 HTML,我们用来替换页面的一部分.另外,我们只需要重定向到登录页面.

This worked for us because all Ajax calls always returned HTML inside a DIV element that we use to replace a piece of the page. Also, we only needed to redirect to the login page.

这篇关于如何在 jQuery Ajax 调用后管理重定向请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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