HTML Anchor tag redirect link after ajax request
我正在尝试编写一种方法来捕获用户在站点菜单上的点击,但是我希望该过程对用户保持沉默,主要是,当用户将鼠标悬停在锚定标记上时,它的行为将正常(显示其中包含的链接)。我已经尝试了各种方法来执行此操作,现在几乎可以正常工作了,我的代码如下:
1 2 3 | Google <img class="childImage" src="icon.png"> |
在jQuery中,我有:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | $(".selectAnchor, .menuAnchor").click(function(event){ event.stopPropagation(); console.log(event.target.nodeName); //event.preventDefault(); $.ajax({ type: 'POST', url: 'http://localsite/menuRedirect.php', data: {id:0, module:'Module',source:'Source'}, complete: function(data){ console.log("DONE"); return true; } }); }); |
该链接重定向到所选页面,但是ajax代码永远不会完成,因此永远不会记录用户的点击。
我尝试使用event.preventDefault,但是无法恢复已取消的事件。
问题的一部分来自额外的功能,例如,大多数用户右键单击定位标记以在新标签页中打开(或使用控制键单击或中键单击),并使用类似
1 | Google |
出于安全原因,不允许在站点上使用
。
有什么建议可以做到吗?
使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | $(".selectAnchor, .menuAnchor").click(function(event){ event.preventDefault(); console.log(event.target.nodeName); var self = this; $.ajax({ type: 'POST', url: 'http://localsite/menuRedirect.php', data: {id:0, module:'Module',source:'Source'}, complete: function(data){ console.log("DONE"); location.href = self.href; } }); }); |
或使用context属性删除
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | $(".selectAnchor, .menuAnchor").click(function(event){ event.preventDefault(); console.log(event.target.nodeName); $.ajax({ type: 'POST', context: this, url: 'http://localsite/menuRedirect.php', data: {id:0, module:'Module',source:'Source'}, complete: function(data){ console.log("DONE"); location.href = this.href; } }); }); |
最新的Chrome浏览器无法完成ajax请求。由于浏览器页面收到了来自用户的新url请求,因此浏览器将立即终止该线程。
98%的情况下,您可以在网络标签中看到ajax请求被取消。
因此解决方案是使用sendBeacon API。这将异步执行POST请求。
Google Analytics(分析)使用此代码执行事件跟踪(例如:点击)。
https://developer.mozilla.org/zh-CN/docs/Web/API/Navigator/sendBeacon
1 | navigator.sendBeacon("{{url}}", param); |
尝试一下
1 2 3 | Google <img class="childImage" src="icon.png"> |
然后在jquery中进行以下操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | $(".selectAnchor, .menuAnchor").click(function(event){ event.preventDefault(); console.log(event.target.nodeName); //event.preventDefault(); $.ajax({ type: 'POST', url: 'http://localsite/menuRedirect.php', data: {id:0, module:'Module',source:'Source'}, complete: function(data){ console.log("DONE"); window.location ="http://www.google.com" } }); }); |