开发者

Issues with tracking clicks on links using jQuery

I have the following code:

<a href="http://mydomain.com/link123" class="someClickEvent">Some Link</a>

$(document).ready(function(){  
    $('.someClickEvent').click(function() {
        var $deal_id = 0;
        var $position = 0;  

       var data = {
           deal_id : $deal_id,
           position : $position                                                              
       };        
        $.ajax({
            type : 'POST',
            data: data,
            url : '/ajax/trackBannerClick',
            success : function(data){
                return true;  
            }
        });             
    });
});

And, it seems that the click event doesn't finish completing before the user is sent to the new URL. Is there a way to make sure the click event has finished prior to sending the user to the new URL? I'd rather not use window.location since it isn't SEO 开发者_如何学运维friendly.


I think that adding async: false might cause the script to wait for the Ajax to complete before calling the success function:

$(document).ready(function(){  
    $('.someClickEvent').click(function() {
        var $deal_id = 0;
        var $position = 0;  

       var data = {
           deal_id : $deal_id,
           position : $position                                                              
       };        
        $.ajax({
            type : 'POST',
            data: data,
            url : '/ajax/trackBannerClick',
            async : false,
            success : function(data){
                return true;  
            }
        });             
    });
});

Reference:

  • $.ajax().


$(document).ready(function(){  
    $('.someClickEvent').click(function(e) {
        e.preventDefault();
        var $deal_id = 0;
        var $position = 0;  
        var data = {
            deal_id : $deal_id,
            position : $position                                                              
    };        
    $.ajax({
        type : 'POST',
        data: data,
        url : '/ajax/trackBannerClick',
        success : function(data){
            window.document.href = $(this).attr('href');
            return true;  
        }
    });            
});


$(document).ready(function(e){  
    $('.someClickEvent').click(function() {
        var $deal_id = 0;
        var $position = 0;  

        //change 1
        var target=jQuery(e.target).attr('href');
        e.preventDefault()

       var data = {
           deal_id : $deal_id,
           position : $position                                                              
       };        
        $.ajax({
            type : 'POST',
            data: data,
            url : '/ajax/trackBannerClick',
            success : function(data){

                //change2
                window.location=target;
                return true;  
            }
        });             
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜