Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
773 views
in Technique[技术] by (71.8m points)

jquery - Redirecting after AJAX post in Django

I use Django's built-in DeleteView and I've assigned a value to the success_url attribute. Now in my template, I trigger this view via JQuery' $.post() method. When the item is deleted, I don't get redirected to the success_url. After some search, I found that it seems to be a problem of AJAX post method, which ignores the redirection.

I fixed it by adding a function to set the window.location="#myRedirectionURL" as the third parameter of $.post() in JQuery.

However, this way seems not very Django. Essentially, it solves the problem from the aspect of AJAX, instead of Django. What's more, it leaves the success_url in DeleteView useless( But you still have to assign a value to success_url, or Django will raise an error).

So is it the right way to get redirected when you post via AJAX? Is there any better way to do it?

Thanks very much.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...