2016-11-30 45 views
-1

我一直在试图让这个简单的代码工作正常,但仍然无法。已经通过多个其他链接。我无法弄清楚我做错了什么。我有一个JavaScript函数submitData(),它只需要调用一个django视图就可以调用ajax post。 django视图基本上只需检查请求是否为post,如果是,则必须重定向到另一个页面。重定向到不同的页面后发送ajax调用django视图

我的javascript函数submitData()如下所示,并且还添加了代码的部分,该代码负责发送csrf令牌以及post请求。

function submitData() 
    { 
     $.post('/loggedin/',{"fname":"name1","lname":"name2"},function(data){ 
     alert("Back from views.py"); 

     }); 
    } 

$(function() { 
     $.ajaxSetup({ 
      headers: { "X-CSRFToken": getCookie("csrftoken") } 
     }); 
    }); 

function getCookie(c_name) 
    { 
     if (document.cookie.length > 0) 
     { 
      c_start = document.cookie.indexOf(c_name + "="); 
      if (c_start != -1) 
      { 
       c_start = c_start + c_name.length + 1; 
       c_end = document.cookie.indexOf(";", c_start); 
       if (c_end == -1) c_end = document.cookie.length; 
       return unescape(document.cookie.substring(c_start,c_end)); 
      } 
     } 
     return ""; 
    } 

在我views.py,我有以下的代码,

def loggedin(request): 
    if request.method == "POST": 
     fname = request.POST.get('fname') 
     print fname #The code comes here, prints the fname 
     args = {} 
     args.update(csrf(request)) 
     return render_to_response('loggedout.html',args,context_instance=RequestContext(request)) #This does not redirect to a different page 
    print "outside in loggedin" 
    args = {} 
    args.update(csrf(request)) 
    return render_to_response('loggedin.html',args, RequestContext(request)) 

post调用时,该FNAME打印但那是假设重定向的功能render_to_response()没有发生发生。而是调用post,并调用post调用“Back from views.py”中的警报语句。我不确定我错过了什么。

+0

请显示'render_to_response'的代码 – Mairaj

+0

'views.py'中的'loggedin()'函数具有'render_to_response'()。我只是使用由django的django.shortcuts库提供的'render_to_response()'函数。代码如? – nidHi

+0

这里根本没有重定向。 –

回答

2

您可以在post使用javascript成功完成后重定向。

function submitData() 
    { 
     $.post('/loggedin/',{"fname":"name1","lname":"name2"},function(data){ 
     alert("Back from views.py"); 
     window.location = 'yourpage.hmtl' 
     }); 
    } 

或者,如果你是在响应发送页面名称,您可以使用data重定向到页面。

+0

但我认为它只是发送回应你的ajax调用。 – Mairaj

+0

这种方式可行......但是不可能从django视图本身做同样的事情吗? – nidHi

+0

我不这么认为,因为你正在发送'ajax'调用,并且ajax应该表现得如此。 – Mairaj