[Answer]-Redirecting to another View in Django

1👍

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.

Leave a comment