如何使用JavaScript刷新页面?


当前回答

有很多方法可以重新加载当前页面,但使用这些方法,您可以看到页面更新,但不会有很少的缓存值,因此要克服这个问题,或者如果您希望发出硬请求,请使用以下代码。

    location.reload(true);
    //Here, it will make a hard request or reload the current page and clear the cache as well.


    location.reload(false); OR location.reload();
    //It can be reload the page with cache

其他回答

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

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

问题应该是,

如何使用JavaScript刷新页面

window.location.href = window.location.href; //This is a possibility
window.location.reload(); //Another possiblity
history.go(0); //And another

你被宠坏了。

$(document).on("click", "#refresh_btn", function(event) 
{
     window.location.replace(window.location.href);
});

使用location.reload()。

例如,要在单击id为“something”的元素时重新加载:

$('#something').click(function() {
    location.reload();
});

reload()函数接受一个可选参数,该参数可以设置为true,以强制从服务器而不是缓存重新加载。该参数默认为false,因此默认情况下页面可以从浏览器的缓存中重新加载。

下面是一个使用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刷新修复了