2015-03-13 136 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