Django:重定向到上一页并保持滚动位置 [英] Django: Redirect to the previous page and keep the scroll position

查看:170
本文介绍了Django:重定向到上一页并保持滚动位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过这个问题,您可以在其中使用以下命令重定向到上一页:

I have seen this question where you can redirect to the previous page using:

返回HttpResponseRedirect(request.META.get('HTTP_REFERER'))

但是有没有办法也可以保持其滚动位置?上面的代码重新加载了页面。

but is there a way to also keep the scroll position that it was at? The above reloads the page afresh.

推荐答案

来回反复,这就是我的想法(在< a href = https://stackoverflow.com/a/43090765/1526703>此答案):

After some back and forth, this is what I came up with (with help from this answer):

from django.http import HttpResponse

def myview (request):
  ..
  ..
  return HttpResponse('<script>history.back();</script>')

此外,请记住历史记录.back()不会重新加载页面。要重新加载页面,我们必须使用 location.reload(),它还可以保持滚动位置,但我们必须以一种巧妙的方式使用它,以免让页面滚动陷入无限循环。所以这就是我要解决的方法(如这个聪明的答案中所述)

Also, keep in mind that history.back() does not 'reload' the page. To also reload the page, we have to use location.reload() which also keeps the scroll position but we have to use it in a clever way so as not to let it go into an infinite loop. So this is what I did to get around it (as mentioned in this clever answer)

<input type="hidden" id="refreshed" value="false">
<script type="text/javascript">
    $(window).load(function(){
        if ($('#refreshed').val() == "false") {
          $('#refreshed').val("true"); 
        }
        else {
          $('#refreshed').val("false");
          location.reload();
        }
      });
</script>

注意:上面使用的是隐藏的输入字段,因为当'

Note: The above is using a hidden input field because the state of the input field would retain when 'back' is invoked.

话虽如此,如果在您的用例中效果更好,那么您可能需要考虑进行Ajax调用,而不是执行上述操作。

All that said, you may want to consider doing an Ajax call if that works better in your use case instead of doing the above.

这篇关于Django:重定向到上一页并保持滚动位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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