没有时间在窗口卸载时发送获取请求 [英] Don't have time to send get request on window unload

查看:28
本文介绍了没有时间在窗口卸载时发送获取请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在用户关闭浏览器窗口时通知服务器.

I want to notify the server on user closes browser window.

我尝试了所有的

$(window).bind("beforeunload", function() {
    $.get("${contextPath}/notify?direction=logout");
});

$(window).unload( function() {
    $.get("${contextPath}/notify?direction=logout");
});

$(window).unload(function() {
    $.ajax({
      url: "${contextPath}/notify?direction=logout"
    });
});

但两者都不能很好地工作,尽管在手册中说它可能应该这样做.

but neither work well, despite the fact, that it is said in manual that it probably should.

在 Firefox 中,我仅在窗口关闭时没有通知,但在页面刷新时有通知.在 Chrome 中,我两者都没有.

In Firefox I have no notifications only on window close, but have ones on page refresh. In Chrome I have neither.

我尝试在 Firebug 或 Chrome 开发者工具中跟踪这个脚本,发现如果被跟踪它就开始工作了!所以我认为它不能正常工作,因为它在窗口关闭或导航之前没有时间发送请求.

I tried to trace this script in Firebug or Chrome Developer Tools and found, that it is starting to work if traced! So I think it does not work normally because it has no time to send request before window closed or navigated.

这是真的吗?如何完成我的任务?

Is this true? How to accomplish my task?

解决方案

这有效:

$(window).bind("beforeunload",
    function() {
        $.ajax({
            async: false,
            url: 'notify'
        });
    }
);

推荐答案

这很棘手,因为浏览器不会等到响应到来,所以 ajax 请求可能会中止.

It is very tricky because the browser will not wait untill the response comes so the ajax request might get aborted.

您可以在 beforeunload 事件中尝试类似的操作.

You can try something like this in beforeunload event.

$(window).bind("beforeunload", function() {
    $.ajax({
        async: false,//This will make sure the browser waits until request completes
        url: "${contextPath}/notify?direction=logout"
    });
});

这篇关于没有时间在窗口卸载时发送获取请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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