我需要在Django中返回return redirect(url)或类似的内容,并强制模板对此URL进行操作。
当需要完全重定向时,它将返回模板html代码。
有任何想法吗?现在,我必须在模板window.location='url'
中编写重定向,它可以工作,但会使代码混乱。
django.__version__ == '2.0.1'
我需要django文字,就像javascript window.location='myurl'
部分视图
@csrf_exempt
def CheckState(request):
...
try:
... if (condition):
a = redirect('/mypage/')
...
return a #redirect('http://localhost:port/mypage/')
模板的一部分(js.code)
$(document).ready(function() {
$.get('/my/CheckState/', {})
.success(function(data){
console.log(data);
//window.location = 'url' works here, otherwice no redirect!
//In console i see html-code of 'http://localhost:port/mypage/'
})
.error(function(xhr, textStatus, errorThrown){
console.log(xhr.responseText);
})
-评论-
a._headers = {'content-type': ('Content-Type': 'text/html; charset=utf-8'),
'location' : ('Location', '/mypage' )}
在我问问题之前,我已经看到了此标头,但是问题仍然存在-没有跳转。为什么这个redirect
无法正常工作?
答案 0 :(得分:0)
无法阻止$.get()
(使用Xmlhttprequest
)跟随重定向。 See this question进行解释。
您也许可以使用fetch
API,该API确实可以防止重定向。
如果无法执行此操作,则可以更改视图以在响应中返回新的URL,
from django.http import JsonResponse
def CheckState(request):
return JsonResponse({'status': 'redirect', 'url': '/new/url/'})
...
然后在您的ajax处理程序中,检查响应的响应是否为status = redirect,如果是,则将url设置为window.location
。