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

jQuery Ajax 401状态码场景下获取响应头location参数实现重定向的方法

解决方案

jQuery Ajax的statusCode回调中接收的第一个参数是jqXHR对象,本身封装了响应头的读取方法,有两种实现方式可选:

方法1:直接调用getResponseHeader方法(推荐)

无需手动解析全量响应头,直接读取指定字段即可,代码最简洁可靠:

$.ajax({
    url: url,
    data: (def.data ? (def.convertToJson ? JSON.stringify(def.data) : def.data) : ''),
    type: def.type,
    dataType: def.dataType,
    cache: def.cache,
    contentType: def.contentType,
    statusCode: {
        401: function (response) {
            // 直接获取location响应头,头名称不区分大小写
            const redirectUrl = response.getResponseHeader('location');
            if (redirectUrl) {
                window.location.href = redirectUrl;
            }
        }
    }
})

方法2:手动解析全量响应头

如果需要同时处理多个响应头,可以使用getAllResponseHeaders拿到所有头字符串后自行拆分解析:

401: function (response) {
    // 获取所有响应头字符串
    const allHeaders = response.getAllResponseHeaders();
    // 按换行拆分每个响应头条目
    const headerList = allHeaders.split('\r\n');
    let redirectUrl = '';
    headerList.forEach(headerItem => {
        if (!headerItem) return;
        // 拆分键、值
        const [key, value] = headerItem.split(': ');
        if (key.toLowerCase() === 'location') {
            redirectUrl = value;
        }
    })
    if (redirectUrl) {
        window.location.href = redirectUrl;
    }
}

注意事项

如果是跨域Ajax请求,需要后端在响应头中额外配置Access-Control-Expose-Headers: location,否则前端JS默认无权限读取非标准暴露的响应头,会返回null。


内容的提问来源于stack exchange,提问作者Mike Flynn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 18:36:03