我已经写了一些代码,我试图用来钉一个访客的ip,以及他们在网站上的时间。代码:
<script>
var startTime = new Date();
window.onbeforeunload = $(function() {
/* var ip = (window.location != window.parent.location) ? document.referrer: document.location; */
/* var ip = "192.168.1.1"; */
var endTime = new Date(); //Get the current time.
var timeSpent = (endTime - startTime); //Find out how long it's been.
var ip = (window.location != window.parent.location) ? document.referrer: document.location;
$(window).load(function(event) {
$.post('ajax.php', {ip: ip, timeSpent: timeSpent});
});
});
</script>
我不明白的是,为什么不等到用户尝试离开站点后再运行此脚本。
有人能帮我让它等到那个时候再运行吗?谢谢!
发布于 2013-03-12 20:59:15
我可以看到这段代码有几个问题。
首先,$(function(){})
是$(document).ready(function(){})
的缩写。这意味着它将在DOM就绪时运行函数,然后返回一个jQuery对象($(document)
)。
其次,不需要$(window).load(function(){})
。我假设当用户离开页面时,DOM已经加载。
第三,window.onbeforeunload
(和window.onunload
)不会等待AJAX调用完成。您可以尝试使用async:false
让它等待(这可能并不适用于所有浏览器)。
$.ajax({
url: 'ajax.php',
data: {ip: ip, timeSpent: timeSpent},
async: false
});
(注意:window.onbeforeunload
并不是在所有的浏览器上都能工作;我知道Opera不会触发它。)
此外,window.onbeforeunload
还用于询问用户是否要离开页面。如果您从将显示给用户的事件返回一个字符串(Firefox中除外)。
如果您想在用户离开页面时发送AJAX调用,我建议使用window.onunload
。
(function(){ // Anonymous function so startTime isn't global
var startTime = new Date();
window.onunload = function() { // set to a function
var endTime = new Date(); //Get the current time.
var timeSpent = (endTime - startTime); //Find out how long it's been.
var ip = (window.location != window.parent.location) ? document.referrer: document.location;
$.ajax({
url: 'ajax.php',
data: {ip: ip, timeSpent: timeSpent},
async: false
});
};
}());
发布于 2013-03-12 20:57:15
你把整件事搞得一团糟。你所需要的是:
var startTime = new Date();
window.onbeforeunload = function() {
var endTime = new Date(); //Get the current time.
var timeSpent = (endTime - startTime); //Find out how long it's been.
var ip = (window.location != window.parent.location) ? document.referrer: document.location;
$.post('ajax.php', {ip: ip, timeSpent: timeSpent});
};
https://stackoverflow.com/questions/15371783
复制