在 JavaScript 中捕获 302 FOUND [英] Catching 302 FOUND in JavaScript

查看:37
本文介绍了在 JavaScript 中捕获 302 FOUND的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 jQuery 向我的服务器发出 AJAX POST 请求,它可以返回状态为 302 的 HTTP 响应.然后 JavaScript 只是向此 URL 发送 GET 请求,而我想将用户重定向到此响应中的 URL.这可能吗?

I use jQuery to make an AJAX POST request to my server, which can return HTTP response with status 302. Then JavaScript just sends GET request to this URL, while I'd like to redirect user to URL in this response. Is this possible?

推荐答案

由于给出的原因,已接受的答案不起作用.我发布了一条评论,其中包含一个问题的链接,该问题描述了绕过浏览器透明处理 302 的问题:

The accepted answer does not work for the reasons given. I posted a comment with a link to a question that described a hack to get round the problem of the 302 being transparently handled by the browser:

如何管理重定向请求一个 jQuery Ajax 调用

然而,这是一个肮脏的黑客,经过大量挖掘后,我发现了我认为更好的解决方案 - 使用 JSON.在这种情况下,您可以使对 ajax 请求的所有响应都包含代码 200,并在响应正文中添加某种 JSON 对象,然后您的 ajax 响应处理程序可以以适当的方式使用该对象.

However, it is a bit of a dirty hack and after much digging around I found what I think is a better solution - use JSON. In this case, you can make all responses to ajax requests have the code 200 and, in the body of the response, you add some sort of JSON object which your ajax response handler can then use in the appropriate manner.

这篇关于在 JavaScript 中捕获 302 FOUND的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆