I read this question and implemented the approach that has been stated regarding setting the response HTTP status code to 278 in order to avoid the browser transparently handling the redirects.
(我阅读了此问题,并实现了关于将响应HTTP状态代码设置为278的方法,以避免浏览器透明地处理重定向。)
Even though this worked, I was a little dissatisfied as it is a bit of a hack.(即使这行得通,我还是有点不满意,因为它有点破烂。)
After more digging around, I ditched this approach and used JSON .
(在深入研究之后,我放弃了这种方法并使用了JSON 。)
In this case, all responses to AJAX requests have the status code 200 and the body of the response contains a JSON object that is constructed on the server.(在这种情况下,对AJAX请求的所有响应都具有状态码 200,并且响应的主体包含在服务器上构造的JSON对象。)
The JavaScript on the client can then use the JSON object to decide what it needs to do.(然后,客户端上的JavaScript可以使用JSON对象来决定它需要做什么。)
I had a similar problem to yours.
(我有一个与您类似的问题。)
I perform an AJAX request that has 2 possible responses: one that redirects the browser to a new page and one that replaces an existing HTML form on the current page with a new one.(我执行一个AJAX请求,该请求有2种可能的响应:一种将浏览器重定向到新页面,另一种将新页面替换当前页面上的现有HTML表单。)
The jQuery code to do this looks something like:(执行此操作的jQuery代码如下所示:)
$.ajax({
type: "POST",
url: reqUrl,
data: reqBody,
dataType: "json",
success: function(data, textStatus) {
if (data.redirect) {
// data.redirect contains the string URL to redirect to
window.location.href = data.redirect;
} else {
// data.form contains the HTML for the replacement form
$("#myform").replaceWith(data.form);
}
}
});
The JSON object "data" is constructed on the server to have 2 members: data.redirect
and data.form
.
(JSON对象“ data”在服务器上构造为具有2个成员: data.redirect
和data.form
。)
I found this approach to be much better.(我发现这种方法要好得多。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…