繁体   English   中英

如何在href属性中获取价值并在Ajax中使用

[英]How to get value in the href attribute and use in ajax

我有一个jquery + ajax代码来跟踪我网站上广告链接的点击。 这是出于测试目的:

$(document).ready(function(){
$(".myadlinks").on("click",function(e){
e.preventDefault();
var d = {id:$(this).attr('id')};
$.ajax({
    type : 'GET',
    url : "adlinktracking.php",
    data : d,
    success : function(responseText){
        if(responseText==1){
            alert('click is saved OK');
            window.location.href = $(this).attr('href');
        }else if(responseText==0){
            alert('click can't be saved.');
        }
        else{
            alert('error with your php code');
        }
    }
});
});
});

当我单击一个广告链接时,它会显示警告:单击已保存,但是然后单击它不会重定向到预期的URL。 我认为这行代码window.location.href = $(this).attr('href');出了点问题window.location.href = $(this).attr('href'); 因为当我尝试替换$(this).attr('href'); 使用“ http://www.google.com ”。 有用。

请帮助...非常感谢

您需要在回调中没有对href属性的引用。 回调中的$(this)不是用户单击的链接。

$(document).ready(function(){
    $(".myadlinks").on("click",function(e){
        e.preventDefault();
        var link = $(this);
        var linkHref = link.attr('href'); //this line is new
        var d = {id: link.attr('id')};

        $.ajax({
            type : 'GET',
            url : "adlinktracking.php",
            data : d,
            success : function(responseText){
                if(responseText==1){
                    alert('click is saved OK');
                    window.location.href = linkHref; //reference to the save href
                } else if(responseText==0){
                    alert('click can't be saved.');
                } else{
                    alert('error with your php code');
                }
            }
        });
    });
});

$(this)不指向成功回调上下文中的链接。 您必须在单独的变量中设置它,并在成功回调中使用它。 检查以下代码。

$(document).ready(function(){
    $(".myadlinks").on("click",function(e){
        e.preventDefault();

        var currentobj = this;
        var d = {id:$(this).attr('id')};
        $.ajax({
            type : 'GET',
            url : "adlinktracking.php",
            data : d,
            success : function(responseText){
                if(responseText==1){
                    alert('click is saved OK');
                    window.location.href = $(currentobj).attr('href');
                }else if(responseText==0){
                    alert('click can't be saved.');
                }
                else{
                    alert('error with your php code');
                }
            }
        });
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM