如何在不刷新页面或更改url的情况下加载不同的html页面?
问题描述:
我想加载一个HTML页面,而不刷新页面或更改其网址。 例如,如果我在http://localhost/sample/home
,并且我想导航到联系我们页面,我单击联系人链接并且联系页面内容被加载而无需刷新页面或更改网址。如何在不刷新页面或更改url的情况下加载不同的html页面?
这是怎么做到的?
答
喜欢的东西:
$('#content').load('ajax/contact.html', function() {
alert('Load was performed.');
});
答
看进用jQuery.load()。
这允许您从URL加载HTML,并将其显示在页面中的元素中。
因此,你可以这样做:
$("body").load("/sample/contactus");
但是我不会推荐这是它不是伟大的SEO或可访问性。此外,它也不会减少加载时间,因为你还需要为一个整体的其他页面中的HTTP请求..
答
模拟HTML:
<div id="links">
<a href="/contactus.html">Contact Us </a>
</div>
<div id="content"></div>
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()
- 负载来自服务器的数据并将返回的HTML放入匹配元素中
http://en.wikipedia.org/wiki/Ajax_(programming) – Utkanos 2012-08-01 11:21:28
http://api.jquery.com/load/ – nbrooks 2012-08-01 11:21:42
或者你可以使用iframe ... – jacktheripper 2012-08-01 11:22:54