简体   繁体   中英

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:

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:

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.

What you supplied as an example in your question relates to the 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> .

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 .

If you want to use it via JavaScript all you need to do is to modify window.location.hash .

The way FaceBook and other sites do it now is better . 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. This changes the url in the address bar with no reload and allows for correct bookmarking and reloading/refreshing.

You do it by requesting the new page with AJAX , and then insert the content into your current page.

Wrote more details about this in this question .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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