我的页面上有一个指向其他网站的 anchor 。
我想跟踪点击那个 anchor ,所以我写了一个小的点击处理程序。
<a href="https://othersite.com" class="js-button">Leave</a>
还有javascript代码...
$(".js-button").on("click", function() {
var name = $(this).data("name");
$.when(
$.ajax({
url : 'statscript.php',
type : 'post',
data : 'name=' + name,
success : function(response) {
}
})
).then();
});
虽然它应该等待 ajax 加载,然后才离开页面,但实际上它不起作用。 statscript.php
甚至没有开始工作,用户离开了页面。
所以如果我用 then 将字符串更改为
).then(alert('hey');
php 脚本工作正常,因为它看起来有时间工作。
那么我在 wait
函数上做错了什么?
最佳答案
最接近您的代码的解决方案是:
您应该使用 e.preventDefault() 来阻止 a 标签的默认操作。
您还应该在完成 时重定向用户。如果您的分析系统出现错误,他不需要知道。
你应该这样做:
$(".js-button").on("click", function(e) {
e.preventDefault();
var name = $(this).data("name"),
href = $(this).attr("href");
$.ajax({
url : 'statscript.php',
type : 'post',
data : 'name=' + name,
complete: function () {
alert('Hey!');
// if you want to redirect the user after the statistics sent:
//window.location.href = href;
}
})
});
关于javascript - jquery:如何等到ajax调用完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23054712/