在 AJAX 中处理来自跨源帖子的重定向
我们正在尝试创建一个将托管在服务器 x.foo.com 上的 RESTful API。客户端 html 应用程序(内置 jquery)将托管在 y.foo.com 上。
我正在通过设置 Access-Control-Allow-Origin 标头来处理跨域问题,如下所述 http ://www.w3.org/TR/cors/。
到目前为止一切顺利,我现在可以成功地从主机 y 到主机 x 进行 AJAX 调用。
然而,我遇到了 POST 请求的问题。对 post 请求的典型响应是重定向。但是,XMLHttpRequest 对象不会遵循跨域重定向,从而导致调用失败。
// Hosted on y.foo.com
$.ajax({
type: "POST",
url : http://x.foo.com/myapp/",
success: function(data) {
alert("success!");
}
});
// Return status: 302
// (Which errors out in firebug)
任何人都知道有什么技术可以处理我从这篇文章中为 y 上托管的客户端获得的重定向(到服务器 x 上的资源)吗?
We are trying to create a RESTful API that will be hosted on server x.foo.com. Client html applications (built in jquery) will be hosted on y.foo.com.
I am dealing with cross-domain issues by setting the Access-Control-Allow-Origin header as described here http://www.w3.org/TR/cors/.
So far so good, and I can now successfully make AJAX calls from host y to host x.
However, I ran into a gotcha with POST requests. The typical response to a post request is a redirect. However, the XMLHttpRequest object will not follow cross domain redirects, thus resulting in a failed call.
// Hosted on y.foo.com
$.ajax({
type: "POST",
url : http://x.foo.com/myapp/",
success: function(data) {
alert("success!");
}
});
// Return status: 302
// (Which errors out in firebug)
Anyone know of any techniques to handle the redirect (to a resource on server x) that I get from this post for a client hosted on y?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
客户端如何为 AJAX 请求发送一个特殊的标头,并且根据它是否是 AJAX 请求,您可以更改响应而不是进行重定向。
How about the client sends a special header for AJAX requests, and depending on whether it's an AJAX request or not, you can change the response instead of doing a redirect.