jquery – 重定向后从XHR对象获取最终URL

前端之家收集整理的这篇文章主要介绍了jquery – 重定向后从XHR对象获取最终URL前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我使用ajax(例如通过jQuery)对实现PRG模式的API执行POST请求.因此它会重定向我:
POST /some/api
HTTP/1.1 303 See Other
Location: /some/other/location

然后jQuery将自动跟随重定向并执行:

GET /some/other/location

然后使用后一个请求的输出调用响应处理程序(成功,失败等).但是,如何在javascript中读取最终资源的位置(在这种情况下是/某些/其他/位置)?

解决方法

据我所知,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();

您的控制台应报告一个或多个网址,其中最后一个网址为:

HTTP(S):// {YOURDOMAIN} /一些/其他/位置

原文链接:https://www.f2er.com/jquery/178204.html

猜你在找的jQuery相关文章