然后通过event
点击您的函数:onclick="req(event, 'name=vm....
那么你的函数就可以event.preventDefault() https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault它,这样点击的默认动作就不会被执行。
现在等待您的网络请求返回(可能想要使用fetch() https://developers.google.com/web/updates/2015/03/introduction-to-fetch,这比旧的简单多了XMLHttpRequest
).
一旦 Promise 解决,触发重定向到目标 URL:
<body>
<a href="?mode=full" onclick="req(event, 'name=vmode&value=full','POST','/cookie')">Promeni rezim prikaza</a>
</body>
<script>
function req(event, data='',method='GET',url='/index.html?test') {
console.debug(event);
event.preventDefault();
fetch(url, {method: "POST"}).then(() => {
location.href = event.target.href;
});
}
</script>
但请考虑到您的用户可能必须在后台等待请求并且不了解发生了什么。
如果您只想发送一些统计数据,您可能需要考虑使用新的sendBeacon() https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeaconAPI。它发送数据(POST
only) async在后台,以便可以为用户加载链接目标,而浏览器则在sendBeacon()
在后台请求。