Django 重定向 - 使用 ajax 时如何处理重定向
Django redirects - how to handle redirect when using ajax
我需要 return redirect(url) 或 django 中的类似内容,并强制模板执行此操作 url.
它 return 是我的模板 html-code 而不是当需要完全重定向时。
有任何想法吗?现在我必须在模板 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' )}
我在问问题之前看到了这个 header,但问题存在 - 没有跳转。为什么这个 redirect
不起作用?
无法阻止 $.get()
(使用 Xmlhttprequest
)跟随重定向。 See this question 求解释。
您可以使用 fetch
API 来防止重定向。
如果您不能这样做,您可以在响应中将视图更改为 return 新的 URL,
from django.http import JsonResponse
def CheckState(request):
return JsonResponse({'status': 'redirect', 'url': '/new/url/'})
...
然后在您的 ajax 处理程序中,检查 status=redirect 的响应,如果是,则将 window.location
设置为 url。
我需要 return redirect(url) 或 django 中的类似内容,并强制模板执行此操作 url.
它 return 是我的模板 html-code 而不是当需要完全重定向时。
有任何想法吗?现在我必须在模板 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' )}
我在问问题之前看到了这个 header,但问题存在 - 没有跳转。为什么这个 redirect
不起作用?
无法阻止 $.get()
(使用 Xmlhttprequest
)跟随重定向。 See this question 求解释。
您可以使用 fetch
API 来防止重定向。
如果您不能这样做,您可以在响应中将视图更改为 return 新的 URL,
from django.http import JsonResponse
def CheckState(request):
return JsonResponse({'status': 'redirect', 'url': '/new/url/'})
...
然后在您的 ajax 处理程序中,检查 status=redirect 的响应,如果是,则将 window.location
设置为 url。