gpt4 book ai didi

jquery - 当 jQuery.post() 请求时,Django View 不会重定向

转载 作者:行者123 更新时间:2023-12-01 02:26:20 25 4
gpt4 key购买 nike

我的 Django 模板中有一个用于切换语言的菜单。我通过 POST 调用如下所示的“/i18n/setlang/” View 来更改语言设置。当我使用 html 表单时,用户会按预期重定向,但当我使用 jQuery.post() 时,情况并非如此。

我错过了什么?

谢谢

使用 jQuery.post() 调用 View :

$.post("/i18n/setlang/", { language: 'en', next: "{{request.path}}" });

View 如下:

def set_language(request):
"""
Redirect to a given url while setting the chosen language in the
session or cookie. The url and the language code need to be
specified in the request parameters.

Since this view changes how the user will see the rest of the site, it must
only be accessed as a POST request. If called as a GET request, it will
redirect to the page in the request (the 'next' parameter) without changing
any state.
"""
next = request.REQUEST.get('next', None)

if not next:
next = request.META.get('HTTP_REFERER', None)
if not next:
next = '/'
response = http.HttpResponseRedirect(next)
if request.method == 'POST':
lang_code = request.POST.get('language', None)
if lang_code and check_for_language(lang_code):
if hasattr(request, 'session'):
request.session['django_language'] = lang_code
else:
response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)
return response

最佳答案

你不需要ajax。只需使用 JavaScript 提交表单即可。您可以隐藏表单。

<a href="#" onclick="setLang('tr');">
<img src="/static/images/l2.png" alt="Türkçe" />
</a>
<a href="#" onclick="setLang('en');">
<img src="/static/images/l1.png" alt="English" />
</a>
<form id="langForm" action="/i18n/setlang/" method="post" style="display:none;">
<select name="language">
<option value="tr">Türkçe</option>
<option value="en">English</option>
</select>
</form>

...

<script type="text/javascript" src="/static/js/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
function setLang(lang){
$('#langForm select').val(lang);
$('#langForm').submit();
return false;
}
</script>

关于jquery - 当 jQuery.post() 请求时,Django View 不会重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2140568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com