ajax 返回重定向作为对 XHR 请求的响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/282429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 10:44:43  来源:igfitidea点击:

Returning redirect as response to XHR request

ajaxhttp

提问by Vasil

What happens if the browser receives a redirect response to an ajax request?

如果浏览器收到对 ajax 请求的重定向响应会发生什么?

回答by greim

What happens if the browser receives a redirect response to an ajax request?

如果浏览器收到对 ajax 请求的重定向响应会发生什么?

If the server sends a redirect (aka a 302 response plus a Location: header) the redirect is automatically followed by the browser. The response to the secondrequest (assuming it also isn't another redirect) is what is exposed to your program.

如果服务器发送重定向(又名 302 响应加上 Location: 标头),则浏览器会自动跟随重定向。对第二个请求的响应(假设它也不是另一个重定向)是向您的程序公开的内容。

In fact, you don't have the ability to detect whether a 302 response has occurred. If the 302 redirect leads to a 200, then your program acts identically as if the original request led directly to a 200.

事实上,您没有能力检测是否发生了 302 响应。如果 302 重定向导致 200,那么您的程序的行为与原始请求直接导致 200 相同。

This has been both my experience and the behavior called out in the spec.

这既是我的经验,也是规范中提到行为

2016 Update:Time has passed, and the good news is that the new fetch() APIis spec'd to offer finer-grained control of how redirects are handled, with default behavior similar to XHR. That said, it only works where fetch() is implemented natively. Polyfill versions of fetch()—which are based on XHR—continue to have XHR's limitations. Fortunately, native browser supportseems to be rounding out nicely.

2016 年更新:时间已经过去,好消息是新的fetch() API被规范为对重定向的处理方式提供更细粒度的控制,默认行为类似于 XHR。也就是说,它仅适用于本机实现 fetch() 的情况。fetch() 的 Polyfill 版本——基于 XHR——仍然有 XHR 的局限性。幸运的是,本地浏览器支持似乎很好。

回答by jishi

The ajax-requestwill follow that redirect afaik. The actual content (.responseText, .responseXML) will be the content from the page you are redirected to.

ajax-request将跟踪该重定向AFAIK。实际内容 ( .responseText, .responseXML) 将是您重定向到的页面中的内容。

You might be able to intercept the redirect (status-code, location-header) on readyState2 or 3, but not sure about it.

您可能能够在2 或 3上拦截重定向 ( status-code, location-header) readyState,但不确定。