如何使用 JavaScript 刷新页面?

发布于 2024-10-25 20:53:17 字数 28 浏览 5 评论 0 原文

如何使用 JavaScript 刷新页面?

How do I refresh a page using JavaScript?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(20

瘫痪情歌 2024-11-01 20:53:17

使用 location.reload()

例如,每当单击带有 id="something" 的元素时重新加载:

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

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

Use location.reload().

For example, to reload whenever an element with id="something" is clicked:

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

The reload() function takes an optional parameter that can be set to true to force a reload from the server rather than the cache. The parameter defaults to false, so by default the page may reload from the browser's cache.

久夏青 2024-11-01 20:53:17

使用 JavaScript 有多种无限种方式刷新页面:

  1. location.reload()
  2. history.go(0)
  3. location.href = location.href
  4. location.href = location.pathname
  5. location.replace(location.pathname)
  6. location.reload(false)< /代码>

    <块引用>

    如果我们需要从
    再次访问网络服务器(例如文档内容
    动态更改)我们会将参数作为 true 传递。

您可以继续发挥创意:

var methods = [
  "location.reload()",
  "history.go(0)",
  "location.href = location.href",
  "location.href = location.pathname",
  "location.replace(location.pathname)",
  "location.reload(false)"
];

var $body = $("body");
for (var i = 0; i < methods.length; ++i) {
  (function(cMethod) {
    $body.append($("<button>", {
      text: cMethod
    }).on("click", function() {
      eval(cMethod); // don't blame me for using eval
    }));
  })(methods[i]);
}
button {
  background: #2ecc71;
  border: 0;
  color: white;
  font-weight: bold;
  font-family: "Monaco", monospace;
  padding: 10px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.5s ease;
  margin: 2px;
}
button:hover {
  background: #27ae60;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

There are multiple unlimited ways to refresh a page with JavaScript:

  1. location.reload()
  2. history.go(0)
  3. location.href = location.href
  4. location.href = location.pathname
  5. location.replace(location.pathname)
  6. location.reload(false)

    If we needed to pull the document from
    the web-server again (such as where the document contents
    change dynamically) we would pass the argument as true.

You can continue the list being creative:

  • window.location = window.location
  • window.self.window.self.window.window.location = window.location
  • ...and other 534 ways

var methods = [
  "location.reload()",
  "history.go(0)",
  "location.href = location.href",
  "location.href = location.pathname",
  "location.replace(location.pathname)",
  "location.reload(false)"
];

var $body = $("body");
for (var i = 0; i < methods.length; ++i) {
  (function(cMethod) {
    $body.append($("<button>", {
      text: cMethod
    }).on("click", function() {
      eval(cMethod); // don't blame me for using eval
    }));
  })(methods[i]);
}
button {
  background: #2ecc71;
  border: 0;
  color: white;
  font-weight: bold;
  font-family: "Monaco", monospace;
  padding: 10px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.5s ease;
  margin: 2px;
}
button:hover {
  background: #27ae60;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

凶凌 2024-11-01 20:53:17

这适用于所有浏览器

location.reload();

This works on all browsers:

location.reload();
岁吢 2024-11-01 20:53:17

我想很多方法都可以:

  • window.location.reload();
  • history.go(0);
  • window.location.href=window.location .href;

Lots of ways will work, I suppose:

  • window.location.reload();
  • history.go(0);
  • window.location.href=window.location.href;
也只是曾经 2024-11-01 20:53:17

如果您使用 jQuery 并且想要异步刷新页面的内容,那么您可以执行以下操作:

$.ajax({
    url: "",
    context: document.body,
    success: function(s,x){
        $(this).html(s);
    }
});

我在这里使用的方法是 Ajax jQuery。我在 Chrome 13 上测试了它。然后我将代码放入将触发重新加载的处理程序中。 URL"",这意味着 此页面

请注意,这可能不是提问者所说的“刷新”的意思。 通常,在常见用法中,该术语是指以用户单击浏览器用户界面中提供的“刷新/重新加载”按钮时浏览器执行的方式重新加载页面。然而,这并不是“刷新”的唯一可能的含义,并且在特定情况下它可能是优选的。

此代码的作用是将新的和更新的内容获取到页面。它通过对新内容发出异步 HTTP 请求,然后用新的异步加载内容替换页面的当前内容来实现此目的。它的结果是刷新页面的内容,尽管它的工作方式略有不同。

您必须选择您真正想要的,以及最适合您的特定用例的。

编辑:问题已更改为“使用 javascript”,因此考虑到问题当前的确切措辞,此答案可能不是最准确的。

If you're using jQuery and you want to refresh the contents of a page asynchronously, then you can do the following:

$.ajax({
    url: "",
    context: document.body,
    success: function(s,x){
        $(this).html(s);
    }
});

The approach here that I used was Ajax jQuery. I tested it on Chrome 13. Then I put the code in the handler that will trigger the reload. The URL is "", which means this page.

Note that this may not be what the asker meant by "refresh". Generally, in common usage, that term refers to reloading the page in the way that the browser would do if the user clicked the "Refresh/reload" button provided in the browser's user interface. However, this is not the only possible meaning of "refresh", and it may be preferred in a specific circumstance.

What this code does is get new and updated content to the page. It does this by making an asynchronous HTTP request for the new content, and then replacing the page's current content with the new asynchronously-loaded content. It has the result of refreshing the contents of the page, even though it works slightly differently.

You'll have to choose which one you actually want, and which works best for your specific use-case.

EDIT: The question has been changed to "using javascript" so this answer might not be the most accurate considering the current exact wording of the question.

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

window.location = window.location.pathname;

因为

window.location.reload();

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

If the current page was loaded by a POST request, you may want to use

window.location = window.location.pathname;

instead of

window.location.reload();

because window.location.reload() will prompt for confirmation if called on a page that was loaded by a POST request.

﹂绝世的画 2024-11-01 20:53:17

你的选择太多了;以下任何工作:

  • window.location.href = window.location.href;
  • window.location.reload();
  • history.go(0);

You're spoiled for choice; any of the following work:

  • window.location.href = window.location.href;
  • window.location.reload();
  • history.go(0);
暗恋未遂 2024-11-01 20:53:17

您可能想要使用

location.reload(forceGet)

forceGet ,它是一个布尔值且可选。

默认值为 false,从缓存中重新加载页面。

如果您想强制浏览器从服务器获取页面以摆脱缓存,请将此参数设置为 true。

或者只是

location.reload()

如果您想要快速轻松地进行缓存。

You may want to use

location.reload(forceGet)

forceGet is a boolean and optional.

The default is false which reloads the page from the cache.

Set this parameter to true if you want to force the browser to get the page from the server to get rid of the cache as well.

Or just

location.reload()

if you want quick and easy with caching.

仅冇旳回忆 2024-11-01 20:53:17

具有不同缓存相关行为的三种方法:

  • location.reload(true)

    在实现了 location.reload()forcedReload 参数的浏览器中,通过获取页​​面及其所有资源(脚本、样式表、图像等)。不会从缓存中提供任何资源 - 从服务器获取新副本,而不发送任何 if-modified-sinceif-none-match请求中的标头。

    相当于用户在可能的情况下在浏览器中进行“硬重新加载”。

    请注意,Firefox 支持将 true 传递给 location.reload()(请参阅 MDN)和 Internet Explorer(请参阅 MSDN),但并未得到普遍支持,并且不是 W3 HTML 5 规范,也不是 W3 草案 HTML 5.1 规范,也不是 WHATWG HTML 生活标准

    在不支持的浏览器(例如 Google Chrome)中,location.reload(true) 的行为与 location.reload() 相同。

  • location.reload()location.reload(false)< /strong>

    重新加载页面,获取页面 HTML 本身的新的、未缓存的副本,并执行 RFC 7234 对浏览器已缓存的任何资源(如脚本)的重新验证请求,即使它们是 新鲜是 RFC 7234 允许浏览器无需重新验证即可提供服务。

    据我所知,浏览器在执行 location.reload() 调用时应如何利用其缓存的确切方式尚未指定或记录;我通过实验确定了上述行为。

    这相当于用户只需按浏览器中的“刷新”按钮。

  • location = location(或无数其他可能的技术,涉及分配给 location 或其属性)

    仅当页面的 URL 不包含 fragid/hashbang 时才有效!

    重新加载页面,而不重新获取或重新验证任何 fresh 从缓存中获取资源。如果页面的 HTML 本身是新鲜的,这将重新加载页面而不执行任何 HTTP 请求。

    这相当于(从缓存的角度来看)用户在新选项卡中打开页面。

    但是,如果页面的 URL 包含哈希值,则这将不起作用。

    同样,据我所知,这里的缓存行为是未指定的;我是通过测试确定的。

因此,总而言之,您希望使用:

  • location = location 来最大限度地利用缓存,只要页面的 URL 中没有哈希值,在这种情况下,location.reload(true) 无法
  • 在不重新验证的情况下获取所有资源的新副本(尽管它并未得到普遍支持,并且其行为与 location.reload()< /code> 在某些浏览器中,例如 Chrome)
  • location.reload() 来忠实地再现用户单击“刷新”按钮的效果。

Three approaches with different cache-related behaviours:

  • location.reload(true)

    In browsers that implement the forcedReload parameter of location.reload(), reloads by fetching a fresh copy of the page and all of its resources (scripts, stylesheets, images, etc.). Will not serve any resources from the cache - gets fresh copies from the server without sending any if-modified-since or if-none-match headers in the request.

    Equivalent to the user doing a "hard reload" in browsers where that's possible.

    Note that passing true to location.reload() is supported in Firefox (see MDN) and Internet Explorer (see MSDN) but is not supported universally and is not part of the W3 HTML 5 spec, nor the W3 draft HTML 5.1 spec, nor the WHATWG HTML Living Standard.

    In unsupporting browsers, like Google Chrome, location.reload(true) behaves the same as location.reload().

  • location.reload() or location.reload(false)

    Reloads the page, fetching a fresh, non-cached copy of the page HTML itself, and performing RFC 7234 revalidation requests for any resources (like scripts) that the browser has cached, even if they are fresh are RFC 7234 permits the browser to serve them without revalidation.

    Exactly how the browser should utilise its cache when performing a location.reload() call isn't specified or documented as far as I can tell; I determined the behaviour above by experimentation.

    This is equivalent to the user simply pressing the "refresh" button in their browser.

  • location = location (or infinitely many other possible techniques that involve assigning to location or to its properties)

    Only works if the page's URL doesn't contain a fragid/hashbang!

    Reloads the page without refetching or revalidating any fresh resources from the cache. If the page's HTML itself is fresh, this will reload the page without performing any HTTP requests at all.

    This is equivalent (from a caching perspective) to the user opening the page in a new tab.

    However, if the page's URL contains a hash, this will have no effect.

    Again, the caching behaviour here is unspecified as far as I know; I determined it by testing.

So, in summary, you want to use:

  • location = location for maximum use of the cache, as long as the page doesn't have a hash in its URL, in which case this won't work
  • location.reload(true) to fetch new copies of all resources without revalidating (although it's not universally supported and will behave no differently to location.reload() in some browsers, like Chrome)
  • location.reload() to faithfully reproduce the effect of the user clicking the 'refresh' button.
神爱温柔 2024-11-01 20:53:17

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

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

window.location.reload() will reload from the server and will load all your data, scripts, images, etc. again.

So if you just want to refresh the HTML, the window.location = document.URL will return much quicker and with less traffic. But it will not reload the page if there is a hash (#) in the URL.

浮光之海 2024-11-01 20:53:17

jQuery Load 函数还可以执行页面刷新:

$('body').load('views/file.html', function () {
    $(this).fadeIn(5000);
});

The jQuery Load function can also perform a page refresh:

$('body').load('views/file.html', function () {
    $(this).fadeIn(5000);
});
爱*していゐ 2024-11-01 20:53:17

由于问题是通用的,让我们尝试总结一下可能的解决方案:

简单的纯 JavaScript 解决方案

最简单的方法是以适当的方式放置单行解决方案:

location.reload();

许多人在这里缺少什么,因为他们希望得到一些“点”是 reload() 函数本身提供了一个布尔值作为参数(详细信息:https://developer.mozilla.org/en-US/docs/Web/API/Location/reload)。

Location.reload()方法从当前位置重新加载资源
网址。它的可选唯一参数是一个布尔值,当它是
true,导致页面始终从服务器重新加载。如果是的话
false 或未指定,浏览器可能会从其重新加载页面
缓存。

这意味着有两种方法:

解决方案 1:强制从服务器重新加载当前页面

location.reload(true);

解决方案 2:从缓存或服务器重新加载(基于浏览器和您的配置)

location.reload(false);
location.reload();

如果您愿意要将其与 jQuery 结合起来监听事件,我建议使用“.on()”方法而不是“.click”或其他事件包装器,例如更合适的解决方案是:

$('#reloadIt').on('eventXyZ', function() {
    location.reload(true);
});

As the question is generic, let's try to sum up possible solutions for the answer:

Simple plain JavaScript Solution:

The easiest way is a one line solution placed in an appropriate way:

location.reload();

What many people are missing here, because they hope to get some "points" is that the reload() function itself offers a Boolean as a parameter (details: https://developer.mozilla.org/en-US/docs/Web/API/Location/reload).

The Location.reload() method reloads the resource from the current
URL. Its optional unique parameter is a Boolean, which, when it is
true, causes the page to always be reloaded from the server. If it is
false or not specified, the browser may reload the page from its
cache.

This means there are two ways:

Solution1: Force reloading the current page from the server

location.reload(true);

Solution2: Reloading from cache or server (based on browser and your config)

location.reload(false);
location.reload();

And if you want to combine it with jQuery an listening to an event, I would recommend using the ".on()" method instead of ".click" or other event wrappers, e.g. a more proper solution would be:

$('#reloadIt').on('eventXyZ', function() {
    location.reload(true);
});
聚集的泪 2024-11-01 20:53:17

这是一个使用 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>

注意:

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

Here is a solution that asynchronously reloads a page using jQuery. It avoids the flicker caused by window.location = window.location. This example shows a page that reloads continuously, as in a dashboard. It is battle-tested and is running on an information display TV in Times Square.

<!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>

Notes:

  • Using $.ajax directly like $.get('',function(data){$(document.body).html(data)}) causes css/js files to get cache-busted, even if you use cache: true, that's why we use parseHTML
  • parseHTML will NOT find a body tag so your whole body needs to go in an extra div, I hope this nugget of knowledge helps you one day, you can guess how we chose the id for that div
  • Use http-equiv="refresh" just in case something goes wrong with javascript/server hiccup, then the page will STILL reload without you getting a phone call
  • This approach probably leaks memory somehow, the http-equiv refresh fixes that
不弃不离 2024-11-01 20:53:17

我发现

window.location.href = "";

或者

window.location.href = null;

还刷新了页面。

这使得重新加载页面并删除任何哈希值变得非常容易。
当我在 iOS 模拟器中使用 AngularJS 时,这非常好,这样我就不必重新运行应用程序。

I found

window.location.href = "";

or

window.location.href = null;

also makes a page refresh.

This makes it very much easier to reload the page removing any hash.
This is very nice when I am using AngularJS in the iOS simulator, so that I don't have to rerun the app.

oО清风挽发oО 2024-11-01 20:53:17

您可以使用 JavaScript location.reload() 方法。
该方法接受一个布尔参数。 truefalse。如果参数为true;该页面总是从服务器重新加载。如果为;这是默认值或使用空参数浏览器从缓存中重新加载页面。

使用 true 参数

<button type="button" onclick="location.reload(true);">Reload page</button>

使用 default/ false 参数

 <button type="button" onclick="location.reload();">Reload page</button>

使用 jquery

<button id="Reloadpage">Reload page</button>
<script type="text/javascript">
    $('#Reloadpage').click(function() {
        location.reload();
    }); 
</script>

You can use JavaScript location.reload() method.
This method accepts a boolean parameter. true or false. If the parameter is true; the page always reloaded from the server. If it is false; which is the default or with empty parameter browser reload the page from it's cache.

With true parameter

<button type="button" onclick="location.reload(true);">Reload page</button>

With default/ false parameter

 <button type="button" onclick="location.reload();">Reload page</button>

Using jquery

<button id="Reloadpage">Reload page</button>
<script type="text/javascript">
    $('#Reloadpage').click(function() {
        location.reload();
    }); 
</script>
爱本泡沫多脆弱 2024-11-01 20:53:17

如果您正在使用 jQuery 并且想要刷新,请尝试在 javascript 函数中添加 jQuery:

我想在单击 oh an h3 时从页面隐藏 iframe,对我来说它有效,但我没有'除非我手动刷新浏览器,否则无法单击允许我查看 iframe 的项目...这并不理想。

我尝试了以下方法:

var hide = () => {
    $("#frame").hide();//jQuery
    location.reload(true);//javascript
};

将普通的 Jane javascript 与您的 jQuery 混合应该可以工作。

// code where hide (where location.reload was used)function was integrated, below    
    iFrameInsert = () => {
        var file = `Fe1FVoW0Nt4`;
        $("#frame").html(`<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/${file}\" frameborder=\"0\" allow=\"autoplay; encrypted-media\" allowfullscreen></iframe><h3>Close Player</h3>`);
        $("h3").enter code hereclick(hide);
}

// View Player 
$("#id-to-be-clicked").click(iFrameInsert);

If you are using jQuery and want to refresh, then try adding your jQuery in a javascript function:

I wanted to hide an iframe from a page when clicking oh an h3, for me it worked but I wasn't able to click the item that allowed me to view the iframe to begin with unless I refreshed the browser manually...not ideal.

I tried the following:

var hide = () => {
    $("#frame").hide();//jQuery
    location.reload(true);//javascript
};

Mixing plain Jane javascript with your jQuery should work.

// code where hide (where location.reload was used)function was integrated, below    
    iFrameInsert = () => {
        var file = `Fe1FVoW0Nt4`;
        $("#frame").html(`<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/${file}\" frameborder=\"0\" allow=\"autoplay; encrypted-media\" allowfullscreen></iframe><h3>Close Player</h3>`);
        $("h3").enter code hereclick(hide);
}

// View Player 
$("#id-to-be-clicked").click(iFrameInsert);
吃兔兔 2024-11-01 20:53:17

您可以用两种方式编写它。第一种是重新加载页面的标准方法,也称为简单刷新

location.reload(); //simple refresh

,另一种称为硬刷新。在这里,您传递布尔表达式并将其设置为 true。这将重新加载页面,破坏旧的缓存并从头开始显示内容。

location.reload(true);//hard refresh

You can write it in two ways. 1st is the standard way of reloading the page also called as simple refresh

location.reload(); //simple refresh

And another is called the hard refresh. Here you pass the boolean expression and set it to true. This will reload the page destroying the older cache and displaying the contents from scratch.

location.reload(true);//hard refresh
终止放荡 2024-11-01 20:53:17

可能最短(12 个字符) - 使用 历史记录

history.go()

Probably shortest (12 chars) - use history

history.go()
川水往事 2024-11-01 20:53:17

它是 JavaScript 中最短的。

window.location = '';

It is shortest in JavaScript.

window.location = '';
国际总奸 2024-11-01 20:53:17

您可以简单地使用location.reload()

document.querySelector("button").addEventListener("mousedown", function () {
  location.reload(); // reloads the page
}, false);
* {
  margin: 0px;
  padding: 0px;
}

button {
  background-color: #90ffc9;
  border: 1px solid #000000;
  border-radius: 4px;
  outline: none;
  padding: 1%;
  top: 50%;
  left: 50%;
  position: absolute;
  transform: translate(-50%, -50%);
  transition: background-color 350ms;
}
button:hover {
  background-color: #80af99;
  cursor: pointer;
}
<button>
  Reload
</button>

You can simply use location.reload().

document.querySelector("button").addEventListener("mousedown", function () {
  location.reload(); // reloads the page
}, false);
* {
  margin: 0px;
  padding: 0px;
}

button {
  background-color: #90ffc9;
  border: 1px solid #000000;
  border-radius: 4px;
  outline: none;
  padding: 1%;
  top: 50%;
  left: 50%;
  position: absolute;
  transform: translate(-50%, -50%);
  transition: background-color 350ms;
}
button:hover {
  background-color: #80af99;
  cursor: pointer;
}
<button>
  Reload
</button>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文