0

大家好,我编写了用于跟踪用户点击链接并将它们记录在 php 页面上的代码。这是我的代码

<!doctype html>
<html>
 <head>
  <meta charset="utf-8">
  <title>Tracking outgoing links with JavaScript and PHP</title>
 </head>
 <body>
  <p><a href="test2.html">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("get.php", { name: "John" }      
    });
   });
  </script>
 </body>
</html>

它正在工作,页面 get.php 已请求但未完成。所以无法保存数据。似乎页面移动得太快了

如何解决这个问题。非常感谢

4

3 回答 3

1

导航离开可能会在 AJAX 请求完全发送之前中止它。为避免这种情况,请不要在请求完成之前加载目标页面:

$('a').click(function(e) {
    e.preventDefault();
    var url = $(this).attr('href');
    $.post("get.php", { name: "John" }, function() {
        location.href = url;
    });
});

但是,中键单击链接不会触发此事件。如果您总是想触发您的事件,请使用mousedown事件并检查e.which. 如果1是左键,您需要e.preventDefault()在 AJAX 请求完成后重定向。如果它2是中间按钮,并且您只需要发送 AJAX 请求而无需执行任何其他操作 - 无论如何,该页面都会在新选项卡中打开。

$('a').on('click mousedown', function(e) {
    if(e.which == '3') {
        return; /* do not handle rightclick */
    }
    else if(e.type == 'click' || e.which == '1') {
        e.preventDefault();
    }
    var url = $(this).attr('href');
    $.post("get.php", { name: "John" }, function() {
        if(e.type == 'click' || e.which == '1') {
            location.href = url;
        }
    });
});
于 2012-05-12T08:58:47.007 回答
0
$('a').click(function() {
    $.post("get.php", { name: "John" }, 
                                      ^ why this comma     
    });

你应该这样做:

$('a').on('click', function(event) {
  var self = $(this);
  event.preventDefault(); // stop the navigation of `a`
  $.post("get.php", { name: "John" },function() {
        location.href = self.attr('href');
  });
});
于 2012-05-12T08:54:30.410 回答
0

试试这个:

$(function() {
    $('a').click(function() {
        var shouldFollowAnchor = false;

        $.ajaxSetup.async = false;

        $.post("get.php", { name: "John" }, function () {
            shouldFollowAnchor = true;
        });

        return shouldFollowAnchor;
    });
});

跳转到页面的原因是当您单击链接时,数据已发布并且您导航到锚元素的 href 属性中的链接。您通过返回 false 来停止关注该链接。此示例脚本等待来自服务器的响应 - 是的,如果您愿意,可以添加一些验证 - 同时您可以显示一些“正在加载...”或发送“发送...”消息,用户会想知道发生了什么。=)

于 2012-05-12T09:10:54.780 回答