点击链接后先执行POST请求再延迟跳转的jQuery实现
实现点击链接先发POST请求再跳转的jQuery方案
要实现点击链接时先完成指定POST请求,再跳转到链接目标地址,你可以按以下方式修改代码,核心是阻止默认跳转、利用POST请求的回调确保执行完成,再加个兜底延迟避免异常情况:
<a href="https://google.com/" class="click" target="_blank">Click me</a> <script> $('.click').click(function(e) { // 先拦住链接的默认跳转行为,不然浏览器会直接跳走 e.preventDefault(); // 把链接的目标地址和打开方式存下来 const targetUrl = $(this).attr('href'); const targetWindow = $(this).attr('target') || '_self'; // 发送POST请求 $.post("https://postsomewhere.de/page=2&sort=price&direction=desc") .done(function() { // 请求成功跑完,再打开目标链接 window.open(targetUrl, targetWindow); }) .fail(function() { // 就算请求失败,也给用户跳过去,避免点了没反应 window.open(targetUrl, targetWindow); }); // 加个兜底延迟,防止请求卡住导致用户一直没反应,时间可按需调 setTimeout(function() { window.open(targetUrl, targetWindow); }, 1000); }); </script>
关键说明
- 必须用
e.preventDefault()阻止默认跳转,否则浏览器会直接执行链接跳转,POST请求大概率还没完成就中断了 - 依赖
$.post的.done()回调是最可靠的方式,能确保请求成功完成后再跳转 .fail()回调处理请求失败场景,避免用户点击后无响应- 兜底的
setTimeout是保险措施,应对请求超时或异常的情况,延迟时间可根据实际请求耗时调整(比如500ms到2000ms)
内容的提问来源于stack exchange,提问作者Jurgen
相关产品推荐
相关产品推荐

