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

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

问题描述

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

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

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

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