Jer*_*oen 8 ajax jquery redirect
假设我使用ajax(例如通过jQuery)对实现PRG模式的API执行POST请求.因此它会重定向我:
POST /some/api
HTTP/1.1 303 See Other
Location: /some/other/location
Run Code Online (Sandbox Code Playgroud)
然后jQuery将自动跟随重定向并执行:
GET /some/other/location
Run Code Online (Sandbox Code Playgroud)
然后使用后一个请求的输出调用响应处理程序(成功,失败等).但是,如何/some/other/location在javascript中读取最终资源(在本例中)的位置?
虽然这是一篇旧帖子,但希望这个更新的(2018 年)答案会对某人有所帮助。请注意,此解决方案不适用于 Internet Explorer(任何版本),并且仅适用于其他浏览器的相对现代版本。
XMLHttpRequest现在公开一个名为 的只读属性responseURL,它在发生任何重定向后返回响应的 URL 。
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com', true);
xhr.onload = function () {
console.log(xhr.responseURL); // Prints http://example.com
};
xhr.send();
Run Code Online (Sandbox Code Playgroud)
请参阅https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseURL 上的文档
据我所知,这个XMLHttpRequest对象是不可能的.但是,如果您在[可信]域中操作,并且如果它是重要信息,则可以使用iframe代替:
var hidden_iframe = document.createElement('iframe');
hidden_iframe.name = 'hidden_iframe';
hidden_iframe.style.display = 'none';
hidden_iframe.onload = function() {
console.log(hidden_iframe.contentWindow.location.toString());
}
document.body.appendChild(hidden_iframe);
var request = document.createElement('form');
request.method = 'post';
request.action = '/some/api';
request.target = 'hidden_iframe';
request.style.display = 'none';
// append INPUTs to the request form here
document.body.appendChild(request);
request.submit();
Run Code Online (Sandbox Code Playgroud)
您的控制台应报告一个或多个网址,其中最后一个网址为:
http(s)://{yourdomain}/some/other/location
我相信这通常是不可能的,尽管我可以通过 Chrome 开发者工具看到浏览器确实从服务器获取了 303 响应,然后遵循重定向。
请参阅此相关问题和答案:Is it possible for XHR HEAD requests to not follow redirects (301 302)