如何使用JavaScript刷新页面?


当前回答

使用location.reload()。

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

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

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

其他回答

您应该使用以下代码

window.location.reload();

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

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

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

window.location = window.location.pathname;

而不是

window.location.reload();

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

下面是一些代码行,您可以使用jQuery重新加载页面。

它使用jQuery包装器并提取本地dom元素。

如果您只想在代码上获得jQuery的感觉,而不关心代码的速度/性能,请使用此选项。

只需从1到10中选择适合您的需求,或者根据模式和之前的答案添加更多内容。

<script>
  $(location)[0].reload(); //1
  $(location).get(0).reload(); //2
  $(window)[0].location.reload(); //3
  $(window).get(0).location.reload(); //4
  $(window)[0].$(location)[0].reload(); //5
  $(window).get(0).$(location)[0].reload(); //6
  $(window)[0].$(location).get(0).reload(); //7
  $(window).get(0).$(location).get(0).reload(); //8
  $(location)[0].href = ''; //9
  $(location).get(0).href = ''; //10
  //... and many other more just follow the pattern.
</script>

您可能需要使用

 location.reload()

或可能需要使用

location.reload(forceGet)

forceGet是一个布尔值,也是可选的。

如果您希望强制浏览器从服务器获取页面,以便同时清除缓存,请将此参数设置为true