jquery - 通过 AJAX 发送重定向响应时如何防止浏览器重定向?

标签 jquery ajax django redirect

我正在尝试使用 Django (1.4.2) 对 Django contact_form 应用程序进行 AJAX 化。我想让 Django 在验证和模板渲染方面承担繁重的工作,这样我就可以保持模板和服务器端的一致。因此,当用户提交表单时,我将返回“部分”模板渲染以注入(inject)到 DOM 中。

几乎有效;表单提交、部分模板呈现并返回、显示验证错误等。但是,一旦表单有效,contact_form 的 View 就会执行 http 重定向。我已将 success_url 设置为重定向到发送的消息 URL。

我希望它在服务器上重定向,返回发送的消息并用它替换表单。然而,这在 Chrome 中正常工作。在 Firefox 和 IE 中,整个浏览器重定向到我发送的消息 URL。

有没有办法让重定向影响 AJAX 响应而不重定向整个浏览器?

最佳答案

这是不可能的。 FF 和 IE 按照 W3 规范正确运行。

这是 W3 XMLHttpRequest specification 第 4.6.4 章的摘录:

4.6.4. Infrastructure for the send() method

  • If the response is an HTTP redirect

    If the redirect does not violate security (it is same origin for instance), infinite loop precautions, and the scheme is supported, transparently follow the redirect while observing the same-origin request event rules.

HTTP 重定向基本上指示客户端向给定位置发出全新的 HTTP GET 请求。您最好的选择是对所需资源进行服务器端包含转发

或者,您也可以让它返回一些 JSON,这应该在某个回调函数中通知您的 jQuery 代码,它应该在 JSON 返回的 URL 上重新触发新的 ajaxical 请求。

但是, future 需要考虑添加一个属性来禁用以下重定向。这是另一个摘录:

Not in this Specification

This specification does not include the following features which are being considered for a future version of this specification:

  • Property to disable following redirects;

关于jquery - 通过 AJAX 发送重定向响应时如何防止浏览器重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3217890/

相关文章:

javascript - 如何删除 Vue.js 中的元素?

python - 在运行 'migrate' 命令之前删除 Django 迁移文件?

javascript - JS 问候语不起作用

jquery - Mapster 填充区域

javascript - 了解里面 this 的用法

jquery - 问题 : Menu UL is always behind jquery dialog

javascript - 标签未解释

javascript - 让 Javascript 执行 Python 脚本

python - 如何使用 Django 功能而不是所有键来索引刚刚选择的 json 键?

linux - 通过 cron 为 django 运行 python 脚本