1.前端JS记录页面访问时间
1.1JQuery版本:
<script type="text/javascript" src="js/jquery.min.js"></script>
<script language=JavaScript>
$(document).ready(function() {
var vTimeStart;
var vTimeEnd;
var vTimeVisit; // 进入页面:记录时间
vTimeStart = new Date(); $(window).bind("beforeunload", function() {
vTimeEnd = new Date();
vTimeVisit = vTimeEnd.getSeconds() - vTimeStart.getSeconds(); alert(vTimeVisit); // 恶心的360必须有返回值,否则不执行
event.returnValue = "访问用时:" + vTimeVisit + "秒";
// return vTimeVisit +'';
});
});
</script>
1.2纯JsvaScript版本:
<script language=JavaScript>
var vTimeStart;
var vTimeEnd;
var vTimeVisit; window.onload = function() {
// 进入页面:记录时间
vTimeStart = new Date();
}
window.onbeforeunload = function() { vTimeEnd = new Date();
vTimeVisit = vTimeEnd.getSeconds() - vTimeStart.getSeconds();
// 恶心的360必须有返回值,否则不执行
event.returnValue = "访问用时:" + vTimeVisit + "秒";
// return vTimeVisit +'';
}
</script>
2.Ajax将页面访问时间发送给服务器(JQuery版本)
回调函数不需要,360的返回值也不需要,因为只要服务器有反应就行了
<script type="text/javascript" src="js/jquery.min.js"></script>
<script language=JavaScript>
$(document).ready(function() {
var vTimeStart;
var vTimeEnd;
var vTimeVisit; // 进入页面:记录时间
vTimeStart = new Date(); $(window).bind("beforeunload", function() {
vTimeEnd = new Date();
vTimeVisit = vTimeEnd.getSeconds() - vTimeStart.getSeconds(); // 将用户行为发送给服务器
$.post("ConductCollectServlet", {
visittime : vTimeVisit,
});
});
});
</script>
服务器端新建ConductCollectServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("收集Servlet:Post");
// 页面访问时间
String strVisitTime =request.getParameter("visittime");
System.out.println(strVisitTime);
}