单击时触发脚本?
问题描述:
说我有一个网址:单击时触发脚本?
<a href="hello.html" id="4298">hello</a>
当用户点击这个链接,我希望它火的脚本关闭使用AJAX,所以我们可以追踪有多少次这样的链接被点击的背后。
我的页面被称为track.php
它将通过GET,track.php?id=4298
拉ID 4298,然后它分别更新数据库。
如何在JavaScript/ajax中编写此代码,以便点击此链接,形式为"onclick event"
,此track.php将在幕后运行?
答
请记住,要在后台执行请求,您需要等待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>
答
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函数。
答
<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>