Django: Redirect to the previous page and keep the scroll position

十年热恋 提交于 2019-12-04 01:52:35

问题


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

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


回答1:


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

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.

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.



来源:https://stackoverflow.com/questions/49569913/django-redirect-to-the-previous-page-and-keep-the-scroll-position

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