Javascript Windows.history.back() + location.reload() jquery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25639290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 21:38:21  来源:igfitidea点击:

Windows.history.back() + location.reload() jquery

javascriptjqueryajax

提问by Julien698

I've a probleme in my code. The aim is to complete a simple form, then you click on a submit button. It do an Ajax resquest to go in the method. On success in the ajax request, i use windows.history.back() to go to the previous page ans here i want to refresh this page, to refresh values which are modificated by the form ! Have you an idea about that ?

我的代码有问题。目的是完成一个简单的表单,然后单击提交按钮。它执行 Ajax 请求以进入该方法。在 ajax 请求成功后,我使用 windows.history.back() 转到上一页,在这里我想刷新此页面,以刷新由表单修改的值!你有什么想法吗?

    $('#form_edit').submit(function (e)
    {
        e.preventDefault();
        $.ajax({
            url: $('#form_edit').attr('action'),
            type: 'POST',
            cache: false,
            data: $(this).serialize(),
            success: function (data) {
                if (data === true) {
                    alert("Modification réussie !");
                    window.history.back();
                    location.reload(); <= on success i want to refresh previous page
                }
                else {
                    alert("Modification échouée !");
                }
            },
            error: function ()
            {
                alert("Modification échouée !");
            }
        })
    })

采纳答案by jbyrne2007

It will have already gone back before it executes the reload.

它会在执行重新加载之前返回。

You would be better off to replace:

你最好更换:

window.history.back();
location.reload(); 

with:

和:

window.location.replace("pagehere.html");

回答by Sender

window.history.back();Sometimes it's an issue with javascript compatibility with ajax call or design-related challenges.

window.history.back();有时这是 javascript 与 ajax 调用或设计相关挑战的兼容性问题。

I would use this below function for go back with the refresh.

我会使用下面的这个函数返回刷新。

function GoBackWithRefresh(event) {
    if ('referrer' in document) {
        window.location = document.referrer;
        /* OR */
        //location.replace(document.referrer);
    } else {
        window.history.back();
    }
}

In your html, use:

在您的 html 中,使用:

<a href="#" onclick="GoBackWithRefresh();return false;">BACK</a>`

For more customization you can use history.jsplugins.

如需更多自定义,您可以使用history.js插件。

回答by Chirag Mehta

Try these ...

试试这些...

Option1

选项1

window.location=document.referrer;

Option2

选项2

window.location.reload(history.back());

回答by Stig Hausberg

You can't do window.history.back(); and location.reload(); in the same function.

你不能做 window.history.back(); 和 location.reload(); 在同一个函数中。

window.history.back() breaks the javascript flow and redirects to previous page, location.reload() is never processed.

window.history.back() 中断了 javascript 流程并重定向到上一页, location.reload() 永远不会被处理。

location.reload() has to be called on the page you redirect to when using window.history.back().

使用 window.history.back() 时,必须在重定向到的页面上调用 location.reload()。

I would used an url to redirect instead of history.back, that gives you both a redirect and refresh.

我会使用一个 url 来重定向而不是 history.back,这会给你一个重定向和刷新。

回答by Inamur Rahman

This is the correct answer. It will refresh the previous page.

这是正确答案。它将刷新上一页。

window.location=document.referrer;

回答by Brandon Hoult

After struggling with this for a few days, it turns out that you can't do a window.location.reload() after a window.history.go(-2), because the code stops running after the window.history.go(-2). Also the html spec basically views a history.go(-2)to the the same as hitting the back button and should retrieve the page as it was instead of as it now may be. There was some talk of setting caching headers in the webserver to turn off caching but I did not want to do this.

在为此苦苦挣扎了几天之后,事实证明您不能在 a 之后执行 window.location.reload() window.history.go(-2),因为代码在 之后停止运行window.history.go(-2)。此外,html 规范基本上将 ahistory.go(-2)视为与点击后退按钮相同,并且应该按原样检索页面,而不是像现在这样。有一些关于在网络服务器中设置缓存标头以关闭缓存的讨论,但我不想这样做。

The solution for me was to use session storage to set a flag in the browser with sessionStorage.setItem('refresh', 'true');Then in the "theme" or the next page that needs to be refreshed do:

我的解决方案是使用会话存储在浏览器中设置一个标志,sessionStorage.setItem('refresh', 'true');然后在“主题”或需要刷新的下一页中执行以下操作:

if (sessionStorage.getItem("refresh") == "true") { 
    sessionStorage.removeItem("refresh"); window.location.reload()
}

So basically tell it to reload in the sessionStorage then check for that at the top of the page that needs to be reloaded.

所以基本上告诉它在 sessionStorage 中重新加载,然后在需要重新加载的页面顶部检查它。

Hope this helps someone with this bit of frustration.

希望这可以帮助有这种挫败感的人。

回答by Sacky San

window.history.back() does not support reload or refresh of the page. But you can use following if you are okay with an extra refresh

window.history.back() 不支持重新加载或刷新页面。但是,如果您可以进行额外的刷新,则可以使用以下内容

window.history.back()
window.location.reload()

However a real complete solution would be as follows: I wrote a service to keep track of previous page and then navigate to that page with reload:true

然而,真正完整的解决方案如下:我编写了一个服务来跟踪上一页,然后使用 reload:true 导航到该页面

Here is how i did it.

这是我如何做到的。

'use strict';

angular.module('tryme5App')
    .factory('RouterTracker', function RouterTracker($rootScope) {
          var routeHistory = [];
          var service = {
            getRouteHistory: getRouteHistory
          };

          $rootScope.$on('$stateChangeSuccess', function (ev, to, toParams, from, fromParams) {
              routeHistory = [];
              routeHistory.push({route: from, routeParams: fromParams});
          });

          function getRouteHistory() {
            return routeHistory;
          }

          return service;       
    });

Make sure you have included this js file from you index.html

确保你已经从 index.html 中包含了这个 js 文件

<script src="scripts/components/util/route.service.js"></script>

Now from you stateprovider or controller you can access this service and navigate

现在,您可以从 stateprovider 或 controller 访问此服务并导航

var routeHistory = RouterTracker.getRouteHistory();    
console.log(routeHistory[0].route.name)
$state.go(routeHistory[0].route.name, null, { reload: true });

or alternatively even perform checks and conditional routing

或者甚至执行检查和条件路由

var routeHistory = RouterTracker.getRouteHistory();    
console.log(routeHistory[0].route.name)
if(routeHistory[0].route.name == 'seat') {
      $state.go('seat', null, { reload: true });
} else {
      window.history.back()
}

Make sure you have added RouterTracker as an argument in your function in my case it was :

确保您已在函数中添加 RouterTracker 作为参数,在我的情况下它是:

.state('seat.new', {
                parent: 'seat',
                url: '/new',
                data: {
                    authorities: ['ROLE_USER'],
                },
                onEnter: ['$stateParams', '$state', '$uibModal', 'RouterTracker', function($stateParams, $state, $uibModal, RouterTracker) {
  $uibModal.open({
      //....Open dialog.....
 }).result.then(function(result) {
            var routeHistory = RouterTracker.getRouteHistory();    
            console.log(routeHistory[0].route.name)
            $state.go(routeHistory[0].route.name, null, { reload: true });
 }, function() {
                    $state.go('^');
 })