$(窗口).unload等待AJAX​​调用前离开网页来完成 [英] $(window).unload wait for AJAX call to finish before leaving a webpage

查看:310
本文介绍了$(窗口).unload等待AJAX​​调用前离开网页来完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,一旦用户离开网页在我的应用程序,我需要调用一个PHP脚本使用AJAX,这将花插入网页上到数据库的时间,然后离开页面。

Basically, once a user leaves a webpage in my application, I need to call a PHP script with AJAX, which will insert a time spent on the webpage to the database and then leave the page.

要等待AJAX​​请求完成,因为在我的应用程序的网页无法访问用户,除非他们已经花了一定时间previous页面上是很重要的(比方说两分钟)。

It is important to wait for the AJAX request to finish because webpages in my application are not accessible to users unless they have spent a certain time on a previous page (let's say two minutes).

下面是我的jQuery code:

Here is my jquery code:

$(document).ready(function() {

    var teid = TEID;
    var startTime = new Date().getTime();

    $(window).unload(function() {
        var timeSpentMilliseconds = new Date().getTime() - startTime;
        var t = timeSpentMilliseconds / 1000 / 60;

        $.ajax({
            type: 'POST',
            url: '/clientarea/utils/record-time',
            data: 'teid=' + teid + '&t=' + t
        });
    });

});

我应该如何改变它,所以它会等待Ajax请求之前离开该网页端?

How should I change it so it will wait for the AJAX request to end before leaving the webpage?

编辑:

或者,它可能会更好(容易)只是让AJAX请求重复每分钟左右。这可能吗?

Or it might be better (easier) to just let the AJAX request be repeated every minute or so. Is that possible?

推荐答案

好了,你可以设置异步:假您的AJAX调用,使浏览器等待请求完成别人做任何事情之前,但请注意,这会挂在浏览器请求的持续时间。

Well, you can set async: false on your AJAX call to make the browser wait for the request to finish before doing anything else, but note that this will 'hang' the browser for the duration of the request.

$.ajax({
    type: 'POST',
    async: false,
    url: '/clientarea/utils/record-time',
    data: 'teid=' + teid + '&t=' + t
});

这本手册:

默认情况下,所有的请求被发送异步(即此设置为true默认情况下)。如果您需要同步请求,请将此选项设置为false。跨域请求和数据类型:JSONP请求不支持同步操作。请注意,同步请求可能会暂时锁定浏览器,禁用任何行动,同时请求被激活。

这篇关于$(窗口).unload等待AJAX​​调用前离开网页来完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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