Redirecting after AJAX post in Django

◇◆丶佛笑我妖孽 提交于 2019-11-28 05:27:05
brunofitas

Ajax will not redirect pages!

What you get from a redirect is the html code from the new page inside the data object on the POST response.

If you know where to redirect the user if whatever action fails, you can simply do something like this:

On the server,

In case you have an error

response = {'status': 0, 'message': _("Your error")} 

If everything went ok

response = {'status': 1, 'message': _("Ok")} # for ok

Send the response:

return HttpResponse(json.dumps(response), content_type='application/json')

on the html page:

$.post( "{% url 'your_url' %}", 
         { csrfmiddlewaretoken: '{{ csrf_token}}' , 
           other_params: JSON.stringify(whatever)
         },  
         function(data) {
             if(data.status == 1){ // meaning that everyhting went ok
                // do something
             }
             else{
                alert(data.message)
                // do your redirect
                window.location('your_url')
             }
        });

If you don't know where to send the user, and you prefer to get that url from the server, just send that as a parameter:

response = {'status': 0, 'message': _("Your error"), 'url':'your_url'} 

then substitute that on window location:

 alert(data.message)
 // do your redirect
 window.location = data.url;

http://hunterford.me/how-to-handle-http-redirects-with--jquery-and-django/

Edit: source unavailable

this one works for me, perhaps looks like hack

django middleware

from django.http import HttpResponseRedirect

class AjaxRedirect(object):
    def process_response(self, request, response):
        if request.is_ajax():
            if type(response) == HttpResponseRedirect:
                response.status_code = 278
        return response

javascript

$(document).ready(function() {
    $(document).ajaxComplete(function(e, xhr, settings) {
        if (xhr.status == 278) {
            window.location.href = xhr.getResponseHeader("Location");
        }
    });
});

django-ajax's ajaxPost allows for redirects if you pass a normal redirect(URL) to it (as a json response). Jquery ajax() methods did not work in my case.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!