[英]Redirecting to another View in Django
I'm trying to redirect to another view in a django app. 我正在尝试重定向到Django应用程序中的另一个视图。 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.
现在,我有一个ajax调用update_view视图,然后从那里尝试重定向到另一个带有game_id的视图,称为gameover。
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. 但是,当我这样做时,它不会加载该页面,并且我尝试过的所有其他技术都始终在URL中包含“ update_view”,这是不正确的,因为url映射使游戏结束了。
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. 因为您是通过Ajax调用视图,所以您需要在客户端进行重定向,方法是传递回URL进行重定向,或者提前知道它。 With that URL, you can change the location in JavaScript.
使用该URL,您可以在JavaScript中更改位置。 I would simply return the url you want to redirect to as JSON.
我只是将您要重定向的URL作为JSON返回。 This example assumes you're using jQuery to make the Ajax call:
此示例假设您使用的是jQuery进行Ajax调用:
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/ . 您可以在此处了解有关jQuery Ajax实现的更多信息: 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. 有一个shothand方法来做帖子
$.post()
,我只是出于示范目的选择使用标准的$.ajax()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.