Tracking outgoing links with Javascript and PHP

大城市里の小女人 提交于 2019-12-05 07:08:52

问题


I have tried it using jQuery but it is not working.

<script>
    $("a").click(function () { 
      $.post("http://www.example.com/trackol.php", {result: "click"
  }, "html");
    });
</script>
<a href="http://www.google.com">out</a>

回答1:


To get the best results you should change two things in your approach

  1. Use onmousedown instead of click - this way you get a few extra milliseconds to complete the tracking request, otherwise the browser might not start the connection to your tracker at all as it is already navigating away from the original page. The downside is that you might get some false-positive counts, since the clicking user might not finish the click (eg. keeps the mousebutton down and moves the cursor away from the link) but overall it's a sacrifice you should be willing to make - considering the better quality of tracking.
  2. Instead of an Ajax call ($.post('...')) use an image pre-fetcher (new Image().src='...'). The fact that the tracker is not an image is not relevant in this case because you don't want to use the resulting "image" anyway, you just want to make a request to the server. Ajax call is a two way connection so it takes a bit more time and might fail if the browser is already navigating away but the image pre-fetcher just sends the request to the server and it doesn't really matter if you get something back or not.

So the solution would be something like this:

<script>
$(document).ready(function() {
    $("a").mousedown(function (){
        new Image().src= "http://www.example.com/trackol.php?result=click";
    });
});
</script>

<a href="http://www.google.com">out</a>



回答2:


Instead of using JavaScript to call a php tracking script, you could just link to your tracking script directly and have it in turn redirect the response to the ultimate destination, something like this:

<a href="http://www.example.com/trackol.php?dest=http://www.google.com">out</a>

and in the PHP script, after you do your tracking stuff:

...
header("Location: $dest");



回答3:


As mentioned, the problem is you’re not running the script after the DOM has loaded. You can fix this by wrapping your jQuery script inside $(function() { }, like so:

This works:

<!doctype html>
<html>
 <head>
  <meta charset="utf-8">
  <title>Tracking outgoing links with JavaScript and PHP</title>
 </head>
 <body>
  <p><a href="http://www.google.com/">Test link to Google</a></p>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
  <script>
   $(function() {
    $('a').click(function() {
     $.post('http://www.example.com/trackol.php', { result: 'click' }, 'html');
    });
   });
  </script>
 </body>
</html>

See it in action here: http://jsbin.com/imomo3



来源:https://stackoverflow.com/questions/2077823/tracking-outgoing-links-with-javascript-and-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!