javascript 使用带有 jQuery 的 Location 标头在 POST 后重定向
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10887614/
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
Redirect after POST using the Location header with jQuery
提问by deamon
I want to redirect to the target using the Location
header with jQuery 1.7.
我想使用Location
带有 jQuery 1.7的标头重定向到目标。
My code looks like this
我的代码看起来像这样
$('#creationLink').click(function(){
$.ajax({
type: 'POST',
url: '/',
success: function(data, textStatus, xhr) {
window.location = xhr.getResponseHeader("Location");
}
})
});
... but it does not work. xhr.getResponseHeader("Location")
is null.
......但它不起作用。xhr.getResponseHeader("Location")
一片空白。
HTTP headers:
HTTP 标头:
POST / HTTP/1.1
Host: localhost:9000
X-Requested-With: XMLHttpRequest
Content-Length: 0
HTTP/1.1 302 Found
Content-Type: text/plain; charset=utf-8
Location: http://localhost:9000/vIRdD0PdWp4/bearbeiten
Content-Length: 0
How can I redirect using the location header?
如何使用位置标头重定向?
回答by Jan Krüger
AFAIK, browsers are supposed to, during an XHR, transparently follow the redirect in the response header. That is, the XHR will actually look at the response, see the Location header, and proceed to magically run a second request for that URI. Only when it has the result of thatwill it give you anything at all, and what it gives you is the result of the secondrequest.
AFAIK,浏览器应该在 XHR 期间透明地遵循响应标头中的重定向。也就是说,XHR 实际上会查看响应,查看 Location 标头,然后继续神奇地运行对该 URI 的第二个请求。只有当它有那个结果时,它才会给你任何东西,它给你的是第二次请求的结果。
So, if you need a redirect feature, you'll have to make the thing you request return the target URI in some other way, e.g. as a JSON response.
因此,如果您需要重定向功能,则必须使您请求的事物以其他方式返回目标 URI,例如作为 JSON 响应。
Seethis stackoverflow solution!
PS. reference: http://www.w3.org/TR/XMLHttpRequest/#infrastructure-for-the-send-method
附注。参考:http: //www.w3.org/TR/XMLHttpRequest/#infrastructure-for-the-send-method