简体   繁体   中英

Redirecting to a different page after post ajax call made to django view

I have been trying to get this simple piece of code working fine, but still am not able to. Have gone through multiple other links. Am not able to figure out what is that I doing wrong. I have a javascript function submitData() which just has to make an ajax post call to a django view. The django view basically just has to check if the request is a post , if it is, it has to redirect to another page.

My javascript function submitData() is as below and have also added the part of code which takes care of sending the csrf token along with the post request.

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 "";
     }

In my views.py , I have the following code,

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))

When the post call is made, the fname is printed but the redirection that is suppose to happen by the function render_to_response() is not happening. Instead the post call is returned and the alert statement in the post call "Back from views.py" is alerted. I am not sure on what I am missing out.

You can redirect after post has successfully completed using javascript.

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

Or if you are sending page name in response you can use data to redirect to page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM