使用jQuery实现AJAX发送POST即走请求后跳转a标签href地址的最佳方案
最优实现方案
核心需求是「POST请求不丢失 + 跳转不阻塞」,优先使用浏览器原生的navigator.sendBeacon API实现,这是专门为日志上报这类「发完就走」场景设计的标准方案,请求不会被页面跳转中断,也不会阻塞主线程影响跳转速度。
最终代码实现
$('.useractivity').on('click', function (e) { e.preventDefault(); const targetHref = $(this).attr('href'); const postData = JSON.stringify({ ResourceURL: window.location.pathname, Tag: $(this).text() }); // 优先使用sendBeacon发送请求 if (navigator.sendBeacon) { const blob = new Blob([postData], {type: 'application/json; charset=utf-8'}); navigator.sendBeacon('@Url.Action("SaveUserActivitylog", "NCCNUserActivity")', blob); // 不需要等待返回,直接跳转 window.location.href = targetHref; return; } // 不支持sendBeacon的老旧浏览器降级方案 $.ajax({ url: '@Url.Action("SaveUserActivitylog", "NCCNUserActivity")', type: "POST", dataType: "json", contentType: "application/json; charset=utf-8", data: postData, // 不管请求成功/失败,都直接跳转,符合post and forget的要求 complete: function() { window.location.href = targetHref; } }); });
方案说明
navigator.sendBeacon是异步执行的,不会阻塞页面跳转流程,同时浏览器会保证在卸载页面前尽量把请求发送完成,日志丢失率远低于普通AJAX- 降级方案中用
complete回调而不是success回调,避免接口报错、超时等异常导致用户无法跳转的问题,符合「发完就走」的需求 - 提前缓存a标签的
href属性,避免回调中this指向变化拿不到目标地址的问题
内容的提问来源于stack exchange,提问作者Jefferson
相关产品推荐
相关产品推荐

