简体   繁体   中英

Redirecting to another View in Django

I'm trying to redirect to another view in a django app. Right now, I have an ajax call to the update_view view and from there I try to redirect to another view called gameover with a game_id.

Currently, I'm trying this:

def update_view(request):
    return HttpResponseRedirect(reverse('gameover', args=(game_id,)))

However, when I do this, it won't load the page and every other technique I've tried always has "update_view" in the URL, which isn't correct as the url mapping has gameover coming off the root.

Thank you for all the help!

Because you're calling the view via Ajax, you would need to do the redirect on the client-side, by passing back the URL to redirect to, or knowing it ahead of time. With that URL, you can change the location in JavaScript. I would simply return the url you want to redirect to as JSON. This example assumes you're using jQuery to make the Ajax call:

import json

def update_view(request):
    # more code
    redirect_url = reverse('gameover', args=(game_id,), kwargs={})
    return HttpResponse(json.dumps({'redirect_url': redirect_url},
        ensure_ascii=False), mimetype='application/json')

(function($) {

    $(function() {
        $.ajax({
            type: 'post',
            url: 'path/to/your/view/',
            dataType: 'json',
            success: function(data, textStatus, jqXHR) {
                window.top.location = data.redirect_url;
            }
        });
    });

})(jQuery)

You can learn more about jQuery's Ajax implementation here: http://api.jquery.com/jQuery.ajax/ . There is a shothand method for doing a post, $.post() , I just chose to use the standard $.ajax() for demonstrative purposes.

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