2015-03-13 142 views
0

我有一个jquery + ajax代码来跟踪点击我网站上的广告链接。这对于测试目的:如何获得href属性的值并在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'); 
     } 
    } 
}); 
}); 
}); 

当我点击广告链接,它显示警报:单击保存确定的,但那么它不会重定向到预期的网址。我认为这行代码window.location.href = $(this).attr('href');有问题。因为当我试图用“http://www.google.com”替换$(this).attr('href');。有用。

请帮助...非常感谢

回答

1

$(this)未指向成功回调上下文中的链接。你必须将它设置为seprate变量,并在成功回调中使用它。检查下面的代码。

$(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'); 
       } 
      } 
     }); 
    }); 
}); 
+0

欢呼声它适用于我......非常感谢 – 2015-03-13 08:38:15

4

你必须回调至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'); 
       } 
      } 
     }); 
    }); 
}); 
+0

请更具体一点,在我的情况下如何引用? – 2015-03-13 08:33:01

+0

window.location.href = $(“。myadlinks”)。attr('href'); 但必须只有一个类myadlinks否则使用ID。 ()。(“click”,function(e){e.preventDefault(); )var link = $(this) ).attr('href'); .... window.location.href = link; – ThanosDi 2015-03-13 08:34:00