说我有一个网址:
<a href="hello.html" id="4298">hello</a>
当有人点击此链接时,我希望它使用ajax关闭脚本,以便我们可以跟踪在场景后点击此链接的次数。
我的页面名为track.php
,它将通过GET track.php?id=4298
提取ID 4298,然后分别更新数据库。
如何在javascript / ajax中对此进行编码,以便在点击此链接时,以"onclick event"
的形式,此track.php将在场景后面运行?
答案 0 :(得分: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>
答案 1 :(得分: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函数。
答案 2 :(得分: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>