You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 17:15:04