AJAX后在Django后重定向 [英] Redirecting after AJAX post in Django

查看:1910
本文介绍了AJAX后在Django后重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Django的内置DeleteView,我已经赋值给 success_url 属性。现在,在我的模板,我触发通过JQuery'$。员额()方法,这个观点。当项目被删除,我不重定向到 success_url 。某些搜索后,我发现,它似乎是AJAX POST方法,而忽略重定向的一个问题。

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.

我固定它通过添加一个函数来设置了window.location =#myRedirectionURL $的第三个参数。后() 在JQuery的。

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

不过,这种方式似乎不是很Django的。本质上,它解决了代替的Django从AJAX的方面的问题,。更重要的是,它留下了 success_url 在DeleteView无用的(但你还是要指定一个值 success_url ,或者Django的会引发错误)。

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

因此​​,它是正确的方法,当你通过AJAX发布到重定向?有没有更好的办法做到这一点?

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

非常感谢。

推荐答案

阿贾克斯将不会重定向页面!

Ajax will not redirect pages!

您从重定向得到的是从开机自检响应数据对象中的新页面的HTML code。

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:

在服务器上,

如果你有一个错误

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

如果一切正常

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

发送响应:

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

在HTML页:

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')
             }
        });

如果你不知道从哪里发送用户,你preFER来获取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)

这篇关于AJAX后在Django后重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆