如何使用JavaScript刷新页面?


当前回答

您不需要jQuery中的任何东西,要使用纯JavaScript重新加载页面,只需在location属性上使用reload函数,如下所示:

window.location.reload();

默认情况下,这将使用浏览器缓存(如果存在)重新加载页面。。。

如果您想强制重新加载页面,只需传递一个true值来重新加载方法,如下所示。。。

window.location.reload(true);

此外,如果您已经在窗口范围内,您可以删除窗口并执行以下操作:

location.reload();

其他回答

下面是一个使用jQuery异步重新加载页面的解决方案。它避免了window.location=window.location引起的闪烁。这个示例显示了一个连续重新加载的页面,就像在仪表板中一样。它经过战斗测试,正在时代广场的信息显示电视上运行。

<!DOCTYPE html>
<html lang="en">
  <head>
    ...
    <meta http-equiv="refresh" content="300">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
    <script>
    function refresh() {
      $.ajax({
        url: "",
        dataType: "text",
        success: function(html) {
          $('#fu').replaceWith($.parseHTML(html));
          setTimeout(refresh,2000);
        }
      });
    }
    refresh();
    </script>
  </head>
  <body>
    <div id="fu">
      ...
    </div>
  </body>
</html>

笔记:

直接像$.get(“”,function(data){$(document.body).html(data)})那样使用$.ajax会导致css/js文件被缓存破坏,即使您使用cache:true,这就是我们使用parseHTML的原因parseHTML不会找到一个body标签,所以你的整个身体都需要放在一个额外的div中,我希望这些知识有一天能帮助你,你可以猜到我们是如何为那个div选择id的使用http equiv=“refresh”,以防javascript/服务器打嗝出现问题,然后页面仍然会重新加载,而不会接到电话这种方法可能会以某种方式泄漏内存,http equiv刷新修复了

window.location.reload()将从服务器重新加载,并将再次加载所有数据、脚本、图像等。

因此,如果您只想刷新HTML,window.location=document.URL将返回得更快,流量更少。但如果URL中有散列(#),则不会重新加载页面。

这适用于所有浏览器:

location.reload();
<i id="refresh" class="fa fa-refresh" aria-hidden="true"></i>

<script>
$(document).on('click','#refresh',function(){
   location.reload(true);
});
</script>

如果当前页面是通过POST请求加载的,您可能需要使用

window.location = window.location.pathname;

而不是

window.location.reload();

因为如果在POST请求加载的页面上调用window.location.reload()将提示确认。