使用 jQuery 和 Pyramid 进行 URL 重定向?
我有一个带有表单的网页金字塔应用程序。我在表单 POST 之后使用了 window.location = XXX,但我被告知这对 SEO 不友好。
因此,我尝试在服务器端进行重定向。我所做的就是在 mydomain.com/redirect 的金字塔应用程序中添加一个视图。访问此地址会向目标页面返回 301:
return HTTPMovedPermanently(location=location)
现在,在我的网页中,我将 jQuery POST 添加到 /redirect 页面。看看 firebug,该帖子确实发生了,它得到了 301 返回,然后我的浏览器获取了目标页面,但没有物理重定向到它 - 我错过了什么?
I have a Pyramid app for a web page with a form. I was using window.location = XXX after the form's POST but I was told that this is not SEO friendly.
Therefore, I am trying to do a redirect on the server side. What I did is add a view in my pyramid app at mydomain.com/redirect. Going to this address returns a 301 to the destination page:
return HTTPMovedPermanently(location=location)
Now, in my web page, I added a jQuery POST to the /redirect page. Looking at firebug, the post does indeed happen, it gets a 301 back, and then my browser GET's the destination page, but doesn't physically redirect to it - what am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当 jQuery 收到 3xx 响应时,它不会重定向浏览器。它只会遵循 AJAX 请求中的重定向。这是 XmlHttpRequest 的标准行为,我很确定它无法更改。
您想要的是要么不使用 JavaScript 提交表单并使用 HTTP 重定向,要么使用 JavaScript 并在收到肯定响应时使用 window.location。
做这种事情的通常方法是假设客户端首先没有 JavaScript。然后,一旦一切都在没有 JavaScript 的情况下正常运行,您就可以在其之上添加 JavaScript,并为拥有 JavaScript 的用户提供更好的体验。
也就是说,如果您打算在表单提交后重定向客户端,则可以不使用 AJAX。如果您需要进行验证,则可以阻止 JavaScript 中的表单提交,直到表单有效。
此外,提交表单后重定向的状态代码通常是 302,而不是 301。
jQuery won't redirect the browser when it receives a 3xx response. It will only follow the redirection in the AJAX request. It's the standard behavior for XmlHttpRequest and I am pretty sure it can't be changed.
What you want is either not submit your form with JavaScript and use a HTTP redirection, or use JavaScript and use window.location when it receives a positive response.
The usual way to do this kind of thing is assume the client does not have JavaScript first. Then once everything works without JavaScript, you add JavaScript over that and make it a better experience for the users that have JavaScript.
That said, if you intend to redirect the client after a form submition, you could simply not use AJAX. If you have validation to do, you can prevent form submition in JavaScript, until the form is valid.
Also, the status code for a redirect after a form is submitted is usualy 302, not 301.