简体   繁体   English

如何在不重新加载当前页面的情况下加载 URL?

[英]How can I load a URL without reloading the current page?

I saw some work around Internet like this:我在互联网上看到了一些像这样的工作:

<a href="./someplace.html"> Link </a>

usually it will be open the link or if JS not active:通常它会打开链接或者如果 JS 不活动:

http://www.domain.com/someplace.html

but when JS active, it's open like this and load external page into same page without page refreshing:但是当 JS 处于活动状态时,它会像这样打开并将外部页面加载到同一页面而不刷新页面:

http://www.domain.com/#/someplace.html

How is it possible?这怎么可能? Can someone help?有人可以帮忙吗?

I tried to Google it first, also search this website, but haven't found a good answer.我先尝试用谷歌搜索,也搜索了这个网站,但没有找到好的答案。

$("a").click(function() {
    var $this = $(this),
        href = $this.attr("href");

    $(document.body).load(href);

    location.href = "#" + href;
});

See jQuery.fn.load for more details.有关详细信息,请参阅jQuery.fn.load

What you supplied as an example in your question relates to the hash .您在问题中作为示例提供的内容与hash相关。

The hash is a hyperlink reference internal to the current document.散列是当前文档内部的超链接引用。

When you see a link using file.html#name_of_smth it is likely that an anchor in that page looks something like <a name='name_of_smth'>blah</a> .当您看到使用file.html#name_of_smth的链接时,该页面中的锚点可能看起来像<a name='name_of_smth'>blah</a>

This is not necessarily a JavaScript thing, it can be used if you construct the anchor with a hash and a name such as exemplified here .这不一定是 JavaScript 的事情,如果您使用散列和名称构造锚点(例如此处示例),则可以使用它。

If you want to use it via JavaScript all you need to do is to modify window.location.hash .如果你想通过 JavaScript 使用它,你需要做的就是修改window.location.hash

The way FaceBook and other sites do it now is better . FaceBook 和其他网站现在的做法更好 They use AJAX to reload data into the page (as exemplified by other answers here) and they use window.history.pushState() as exemplified here to inform the browser that the new data belongs to a different url.他们使用 AJAX 将数据重新加载到页面中(如此处的其他答案所示),并使用window.history.pushState()作为示例以通知浏览器新数据属于不同的 url。 This changes the url in the address bar with no reload and allows for correct bookmarking and reloading/refreshing.这会在不重新加载的情况下更改地址栏中的 url,并允许正确的书签和重新加载/刷新。

You do it by requesting the new page with AJAX , and then insert the content into your current page.您可以通过使用AJAX请求新页面,然后将内容插入当前页面来实现。

Wrote more details about this in this question .这个问题中写了更多关于这个的细节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM