gpt4 book ai didi

javascript - 点击 标签时的事件顺序

转载 作者:行者123 更新时间:2023-11-29 20:13:25 30 4
gpt4 key购买 nike

所以我的网站上有一个正常的链接,我想为它添加跟踪。我可以设想很多方法来做到这一点,但我已经确定通过编写一个小的 jquery 函数并在我的标签中放置一个小片段来实现这一点非常简单:

<a href="newpage.html" onclick="saveClick(paramofpageclickhere);">click me!</a>

JavaScript:

function saveClick(someparamhere){
$.ajax({
url: "somepage.php",
data: {param:someparamhere}
});
}

现在,我知道我的语法可能不好,我只是在这里询问整体概念。当您单击链接时,我希望 javascript 发出对 saveClick 的调用,它会立即进行 ajax 调用。没有成功处理程序,因为我真的不在乎是否返回或返回什么。我会让 somepage.php 记录事件。然后,在所有这些之后,我希望标签转到它的 href。

是这样吗?在文档转到其他页面之前是否会发出 ajax 调用?这在所有情况下都有效吗?

有没有人做过这样的事情?任何经验将不胜感激....

最佳答案

如果你想确保 AJAX 调用通过,你可以这样做:

<a href="newpage.html" data-parameters="paramofpageclickhere">click me!</a>

$('[data-parameters]').bind('click', function (event) {
//cache this element to use in AJAX function
var $this = $(this);

//prevent the default naviation
event.preventDefault();

$.ajax({
url: "somepage.php",
data: {param:$this.attr('data-parameters')}
success : function () {

//now navigate to the requested page
location = $this[0].href;
}
});
});

更新

$.ajax() 公开了一个timeout 函数:

timeoutNumber

Set a timeout (in milliseconds) for the request. This will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent. In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period.

因此您可以设置一个timeout 和一个模仿success 函数的error 函数。该文档确实指出:请求在发送之前可能会超时但是如果您的超时是一个非常小的(可能为零)延迟,那么它可能减少用户点击链接和浏览器加载新页面之间的延迟。

30 4 0