基本上,一旦用户在我的应用程序中留下网页,我需要使用AJAX调用PHP脚本,这将在网页上花费一些时间到数据库,然后离开页面.
等待AJAX请求完成非常重要,因为用户无法访问我的应用程序中的网页,除非他们在前一页上花了一定时间(比方说两分钟).
这是我的jquery代码:
$(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
});
});
});
Run Code Online (Sandbox Code Playgroud)
我应该如何更改它以便在离开网页之前等待AJAX请求结束?
编辑:
或者更好(更容易)让AJAX请求每分钟重复一次.那可能吗?
我正在尝试在卸载页面之前对服务器发帖,然后我按照这个并且它工作正常.我的问题是关于window.unload的$.员额被触发后它已卸载.我尝试使用注销链接并检查我的日志,我得到以下内容:
Started GET "/signout" for 127.0.0.1 at 2012-11-22 00:15:08 +0800
Processing by SessionsController#destroy as HTML
Redirected to http://localhost:3000/
Completed 302 Found in 1ms
Started GET "/" for 127.0.0.1 at 2012-11-22 00:15:08 +0800
Processing by HomeController#index as HTML
Rendered home/index.html.erb within layouts/application (0.4ms)
Rendered layouts/_messages.html.erb (0.1ms)
Completed 200 OK in 13ms (Views: 12.9ms)
Started POST "/unloading" for 127.0.0.1 at 2012-11-22 00:15:08 +0800
Processing by HomeController#unloading as */*
Parameters: {"p1"=>"1"}
WARNING: Can't verify CSRF token authenticity
Completed 500 …Run Code Online (Sandbox Code Playgroud)