Django重定向如何在使用ajax时处理重定向

2024-09-30 06:26:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在django中返回重定向(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代码)你知道吗

$(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不起作用?你知道吗


Tags: django代码模板localhosthttpurlhtmlfunction
1条回答
网友
1楼 · 发布于 2024-09-30 06:26:46

无法阻止$.get()(使用Xmlhttprequest)跟随重定向。See this question解释一下。你知道吗

您可以使用fetchAPI,它允许您防止重定向。你知道吗

如果做不到这一点,可以更改视图以在响应中返回新的URL

from django.http import JsonResponse

def CheckState(request):
    return JsonResponse({'status': 'redirect', 'url': '/new/url/'}) 
   ...

然后在ajax处理程序中,检查status=redirect的响应,如果是,则将window.location设置为url。你知道吗

相关问题 更多 >

    热门问题