2011-04-20 67 views
1

說我有一個網址:單擊時觸發腳本?

<a href="hello.html" id="4298">hello</a> 

當用戶點擊這個鏈接,我希望它火的腳本關閉使用AJAX,所以我們可以追蹤有多少次這樣的鏈接被點擊的背後。

我的頁面被稱爲track.php它將通過GET,track.php?id=4298拉ID 4298,然後它分別更新數據庫。

如何在JavaScript/ajax中編寫此代碼,以便點擊此鏈接,形式爲"onclick event",此track.php將在幕後運行?

回答

1

請記住,要在後臺執行請求,您需要等待AJAX​​響應進行點擊操作。如果這就是你想要的,那麼使用jQuery:

<script type="text/javascript"> 
var track = function(obj) { 
    $.ajax({ 
    url: "track.php?id="+obj.id, 
    success: function(){ 
     window.location.href = obj.href; 
    } 
    }); 
    return false; 
}; 
$('a').click(track); 
</script> 
0
var anchors = document.body.getElementsByTagName('a'); 

for (var i = 0, anchorsLength = anchors.length; i < anchorsLength; i++) { 

    a.onclick = function(event) { 

     event.preventDefault(); 
     var id = this.id, 
      xhr = new XMLHttpRequest(); 

     xhr.open('track.php?id=' + id); 

     xhr.onreadystatechange = function() { 
      if (xhr.readyState == 4) { 
      if(xhr.status == 200) { 
       window.location = this.href; 
      } 
      } 
     } 
     xhr.send(); 
    } 
} 

請記住,XMLHttpRequest()不支持舊版本的IE。

如果您使用jQuery,請使用庫的AJAX函數。

0
<script> 
    window.doTheThing = function() { 
     //send a request to your 'track.php' URL here 
    }; 
</script> 

<a href="hello.html" id="4298" onclick="doTheThing(); return false;">hello</a>