【发布时间】:2016-02-01 22:50:38
【问题描述】:
这与我最后一年的 Web 开发项目有关。我想在不重新加载页面的情况下更改页面的内容-我知道这可以使用 css /ajax 或 jquery 来实现,但这只能通过 jquery 中的隐藏和显示或 replaceWith() 来实现。 我希望网址也可以更改。我想实现类似这个页面https://www.khanacademy.org/computing/computer-programming - 当用户点击 INTRO TO JS:Drawing and Animation 时,你会看到页面的 url 和内容发生变化,但页面不会重新加载。
指南将不胜感激。谢谢
一个小草稿:
**MY header.php**
<script language="javascript" src="jquery-1.4.4.min.js"></script>
<script>
$(function(){
$("a[rel='tab']").click(function(e){
//e.preventDefault();
/*
if uncomment the above line, html5 nonsupported browers won't change the url but will display the ajax content;
if commented, html5 nonsupported browers will reload the page to the specified link.
*/
//get the link location that was clicked
pageurl = $(this).attr('href');
//to get the ajax content and display in div with id 'content'
$.ajax({url:pageurl+'?rel=tab',success: function(data){
$('#content').html(data);
}});
//to change the browser URL to 'pageurl'
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
return false;
});
});
/* the below code is to override back button to get the ajax content without reload*/
$(window).bind('popstate', function() {
$.ajax({url:location.pathname+'?rel=tab',success: function(data){
$('#content').html(data);
}});
});
</script>
<div id='menu'>
<a rel='tab' href='http://localhost/html5-history-api/menu1.php'>menu1</a> |
<a rel='tab' href='http://localhost/html5-history-api/menu2.php'>menu2</a> |
<a rel='tab' href='http://localhost/html5-history-api/menu3.php'>menu3</a></div>
我的 menu1.php(menu2 和 3 的代码相同)
<?php
if($_GET['rel']!='tab'){
include 'header.php';
echo "<div id='content'>";
}
?>
menu1 content in menu1.php
<?php
if($_GET['rel']!='tab'){
echo "</div>";
include 'footer.php';
}?>
当我点击链接时,我想要 - 链接消失,它只显示“menu1.php 中的菜单 1 内容”之类的内容,页面上没有其他内容
【问题讨论】:
-
您要更改网址并且不会重新加载整个页面?
-
查看 Angular JS,更具体地说,查看名为
Single page applications (SPA)的概念。 Gmail、facebook 等现在都在使用相同的架构 -
@JohnReyM.Baylen :是的,状态可以推送到 URL 而无需重新加载页面。
-
@JohnReyM.Baylen 是的,约翰它会更改 url 并更改页面内容而无需重新加载
标签: javascript jquery html css ajax