javascript 如何在不刷新页面或更改 url 的情况下加载不同的 html 页面?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11758111/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:14:59  来源:igfitidea点击:

how to load a different html page without refreshing the page or changing the url?

javascriptjqueryajax

提问by Sami

I want to load an html page without refreshing the page or changing its url. So for example, If I am at http://localhost/sample/homeand I want to navigate to contact us page, I click on the contact link and the contact page content gets loaded without refreshing the page or changing the url.

我想在不刷新页面或更改其 url 的情况下加载 html 页面。例如,如果我在http://localhost/sample/home并且我想导航到联系我们页面,我点击联系链接,联系页面内容被加载,而无需刷新页面或更改 url。

How this can be done?

如何做到这一点?

回答by Curt

Look into the use of jQuery.load().

查看jQuery.load()的使用。

This allows you to load HTML from a URL, and display it in an element in your page.

这允许您从 URL 加载 HTML,并将其显示在页面的元素中。

Therefore you could do something like:

因此,您可以执行以下操作:

$("body").load("/sample/contactus");


However I wouldn't recommend this as its not great for SEO or accessibility. Also it wouldn't reduce load time because you still need to make a HTTP Request for a whole other page..

但是我不会推荐这个,因为它对 SEO 或可访问性不是很好。它也不会减少加载时间,因为您仍然需要为整个其他页面发出 HTTP 请求。

回答by nbrooks

Mock HTML:

模拟 HTML:

<div id="links">
    <a href="/contactus.html">Contact Us </a>
</div>
<div id="content"></div>

JS:

JS:

$(function() {
    $("#links > a").click(function(e) {
        e.preventDefault(); //so the browser doesn't follow the link

        $("#content").load(this.href, function() {
            //execute here after load completed
        });
    });
});

jQuery .load()- Load data from the server and place the returned HTML into the matched element

jQuery.load()- 从服务器加载数据并将返回的 HTML 放入匹配的元素中

回答by LiamB

Something like :

就像是 :

$('#content').load('ajax/contact.html', function() {
  alert('Load was performed.');
});

http://api.jquery.com/load/

http://api.jquery.com/load/