jQuery Ajax状态码302捕获失效问题求助
问题根源:浏览器自动吃掉了你的302重定向
我之前也踩过这个坑!当服务器返回302/301状态码时,浏览器会自动完成重定向跳转,然后把跳转后目标页面的响应(通常是200状态)返回给jQuery的Ajax。这就导致你的statusCode里的302/301回调根本没机会执行——Ajax拿到的已经是重定向后的结果了。
几种靠谱的解决方案
方案1:让服务器返回401未授权状态码(最推荐)
会话过期本质上是用户未授权访问资源,返回401才是符合HTTP规范的做法。这样你可以在Ajax的error回调里精准捕获:
$.ajax(this.action, { type: "POST", data: {value: input}, success: function(response){ $('#obtained').val(response); }, error: function(xhr){ // 捕获401状态,跳转首页 if(xhr.status === 401){ window.location.replace('/'); } else { alert(`请求出错:${xhr.statusText}`); } } });
方案2:如果没法改服务器,检查响应内容
如果你暂时没法调整服务器的返回逻辑,可以在success回调里判断返回的内容是不是重定向后的页面(比如登录页)。比如检查响应里是否包含登录表单的标识:
$.ajax(this.action, { type: "POST", data: {value: input}, success: function(response){ // 假设登录页有特定的表单ID,以此判断是否跳转 if(response.includes('<form id="login-form">')){ window.location.replace('/'); return; } $('#obtained').val(response); }, error: function(error){ alert(error); } });
方案3:原生XHR手动禁用重定向(不推荐,兼容性差)
部分浏览器支持通过原生XHR的followRedirects属性关闭自动重定向,但这个属性不是标准API,不同浏览器支持情况不一,所以只作为最后的备选:
const xhr = new XMLHttpRequest(); xhr.open('POST', this.action, true); xhr.followRedirects = false; // 注意:Chrome、Firefox支持,IE不支持 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status === 302 || xhr.status === 301) { window.location.replace('/'); } else if (xhr.status === 200) { $('#obtained').val(xhr.responseText); } else { alert(`请求出错:${xhr.statusText}`); } } }; xhr.send(`value=${encodeURIComponent(input)}`);
总结
优先选择方案1,既符合HTTP规范,也最稳定可靠。方案2是妥协下的可行办法,方案3因为兼容性问题,除非万不得已不建议使用。
内容的提问来源于stack exchange,提问作者Fede E.
相关产品推荐
相关产品推荐

