背景:业务需求是,一个前端(手机和浏览器)HTML页面中有图片,按钮......,需要统计用户点击图片或者按钮的次数。
前端实现:通过一个js来统计HTML页面中所有的图片和按钮对象,并给每个对象赋予一个监听事件,这样当用户点击图片或按钮,就能监听到该事件,并行后台发送一个请求。
var xhr;//创建httpRequest对象 if (window.XMLHttpRequest) { //兼容处理 xhr = new XMLHttpRequest(); } else { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } var url = "http://172.16.11.107:8700/tfcarepoint/send2"; var sendData = function(data, url2, callBackFun) { xhr.open("post", url2, true); //打开连接 xhr.setRequestHeader(‘Content-Type‘, ‘application/json;charset=UTF-8‘); //设置请求头 xhr.send(JSON.stringify({ //设置请求体,并发送请求 "id" : location.href.slice(location.href.lastIndexOf("/") + 1,location.href.lastIndexOf(".")), //"id" : "123", "title" : document.title, "type" : data, "uuId" : uuid, "userId" : userId, "extInfo" : extInfo })); // 回调接口 xhr.onreadystatechange = function() { //设置回调事件 if (xhr.readyState == 4) {// 4 = "loaded" if (xhr.status == 200) {// 200 = OK if (callBackFun) { callBackFun(); } } } }; }; var pviews = "http://172.16.11.107:8700/tfcarepoint/pviews"; (function() { sendData("enter",url); //当页面进入发送有个enter类型的请求 sendData("enter", pviews, function() { alert("当前阅读量为:" + xhr.response); var readNum = document.getElementById("readNum"); if (readNum) { readNumss.textContent = xhr.response; } }); })(); var isMobile = /(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent) || /(Android)/i.test(navigator.userAgent); //获取手机类型 var imgs = document.querySelectorAll("img"); //获取页面中所有的图片 if (imgs) { imgs.forEach(function(val, idx, arr) { //遍历所有的图片对象(img标签),并给每个对象赋予以一个监听事件 var params = val.title ? val.title : "第" + (Number(idx) + 1) + "张图片"; if (isMobile) { val.addEventListener("touchstart", function() { //手机添加触摸事件 sendData("imgs",url); //向后台发送imgs类型的请求 }); } else { val.addEventListener("mousedown", function() { sendData(params,url); }); } }) } var thisPage = false; window.onbeforeunload = function checkLeave(e) { var evt = e ? e : (window.event ? window.event : null); if (!thisPage) { sendData("页面关闭"); } };
原文:https://www.cnblogs.com/jinliang374003909/p/10438418.html