有人可以帮助我使用我的脚本Ajax吗?我想计算访问者在我的网站上花费的时间并将变量发送到PHP页面:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
var start;
$(document).ready(function() {
start = Date.getTime();
$(window).unload(function() {
end = Date.getTime();
$.ajax({
url: 'timer.php',
type:'POST',
async: false,
data: {
'timeSpent': end - start,
x:'hello'
}
})
});
}
在timer.php中,我把:
答案 0 :(得分:1)
您似乎错误输入了类型attr:type =&#39; POST&#39;应输入:&#39; POST&#39;
编辑:仔细观察(此外,在您选择的DevTool中进行检查),会出现更多..
1)start = Date.getTime();是不适合你的。首先将一个新的Date()对象分配给startDate变量,然后将其getTime()返回给变量start 你应该对你的最终变量值做同样的事情,顺便说一句,你最好通过调用var end来定义,就像你使用start一样。并非所有浏览器都严格遵守此规范,但它会为您的代码/编码一致性带来奇迹。
2)窗口卸载事件监听器块不必在文档就绪监听器中,这也似乎是你忽略了正确关闭..
所以试试这个:
var start, end, timeSpent;
$(document).ready( function() {
var dStart = new Date();
start = dStart.getTime();
});
$(window).unload(function() {
var dEnd = new Date();
end = dEnd.getTime();
timeSpent = end - start;
$.ajax({
url: 'timer.php',
type: 'POST',
async: false,
data: {
timeSpent: timeSpent,
x: 'hello'
},
success: function(){
console.log('yay');
}
});
});