JS onunload事件并不总是有效 [英] JS onunload event won't always work
问题描述
我想计算访问者在特定页面上花费的时间并将其存储在我的MySQL数据库中。
I want to count how much time visitors spend on a certain page and store it in my MySQL DB.
我想在window.onload上启动一个计时器像这样:
I thought of just starting a timer on window.onload like this:
window.onload= startCount;
window.onunload= sendCount;
var b=0;
var y;
function startCount() {
document.getElementById('livecount').innerHTML=b;
b=b+1;
y=setTimeout("startCount()",1000);
}
在访问者离开页面后(window.onunload),我是通过XMLHttpRequest将时间发送到PHP文件,该文件将其存储在我的数据库中:
and after the visitor leaves the page (window.onunload), I'm sending the time through an XMLHttpRequest to a PHP file, which will store it in my DB:
function sendCount() {
clearTimeout(y);
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","count.php?q="+b,true);
xmlhttp.send();
}
问题是它并不总是有效。我会说它的效果就像我尝试过的10次中的3次。
可能没有足够的时间让PHP和SQL完全执行了吗?
The problem is it doesn't always work. I would say it works like 3 out of 10 times I try it. Could it be that there is not enough time left for the PHP and SQL to be completely executed?
推荐答案
由于onunload不可靠,我会考虑使用AJAX解决方案。我根本不是这方面的专家,但想到的是每隔一段时间对你的柜台进行一次ping操作。我不会每秒都对你的计数器进行ping操作,因为这似乎过多了。
As onunload is unreliable, I would consider an AJAX solution. I am not an expert in this at all, but the thought that comes to mind is a ping to your counter every so often. I wouldn't ping your counter every second, as that seems excessive.
我会将时间分解为你关心的持续时间,例如< 5秒,< 30秒,< 1分钟,< 5分钟,5 +分钟。
I would break down times into durations you care about, such as <5 seconds, <30 seconds, <1 minute, <5 minutes, 5+ minutes.
然后我会像这样编写一段JavaScript:
Then I would write a piece of JavaScript like so:
window.onload = soCounter;
var iter=0;
var times=[0,5,30,60,300]; // Your duration choices
function doCounter() {
sendCountPing(times(iter));
iter++;
if(iter < times.length) {
setTimeout(doCounter, times[iter]*1000);
}
}
function sendCountPing(dur) {
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{ // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","count.php?q="+b,true);
xmlhttp.send();
}
诀窍在于每个 count.php?q = 30
发送后,您需要从 count.php?q = 5
计数中减去一个。这不一定是程序化的,很容易进行后期处理。
The trick is that for every count.php?q=30
that gets sent, you need to subtract one from the count.php?q=5
count. This does not have to be programmatic, it is easily post-processed.
澄清一下,如果你有3个访客,一个花3秒,一个花20秒,一个花30分钟,你会看到以下计数:
To clarify, if you had 3 visitors, one spending 3 seconds, one spending 20 seconds, and one spending 30 minutes, you would see the following counts:
0: 3 // 3 people spent at least 0 seconds
5: 2 // 2 people spent at least 5 seconds
30: 1
60: 1
300: 1 // 1 person spent at least 5 minutes
有意义吗?
这篇关于JS onunload事件并不总是有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!