更改网址并更新页面内容而无需重新加载

时间:2015-11-02 05:05:26

标签: javascript jquery html css ajax

这与我关于网络开发的最后一年项目有关。我想在不重新加载页面的情况下更改页面内容 - 我知道这可以使用css / ajax或jquery来实现,但这只能通过jquery中的hide和show或replaceWith()实现。 我希望网址也能改变。我希望实现类似这样的页面https://www.khanacademy.org/computing/computer-programming - 当用户点击INTRO TO JS:绘图和动画时,您将看到页面更改的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>
&#13;
&#13;
&#13;

我的menu1.php(menu2和3是相同的代码)

&#13;
&#13;
<?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';
}?>
&#13;
&#13;
&#13;

我希望当我点击链接时 - 该链接消失,它只显示类似于&#34; menu1内容在menu1.php&#34;仅在页面上没有其他内容

2 个答案:

答案 0 :(得分:0)

如果您使用的是Chrome浏览器,请右键单击该div并使用选项&#34;检查元素&#34;。这些是Web开发人员的便捷工具。你提到的链接只是一个超链接,因为它是同一个域下的非常简单的静态页面,使用相同的资源(css,js),它的加载非常快,你会得到一个没有页面加载的印象。{{3} }

答案 1 :(得分:0)

我相信我从链接网站上复制的这个脚本解释了他们如何替换网址。要跟踪位置,他们使用localStorage来跟踪页面位置和其他内容。转到页面并导航到您引用的链接。然后打开控制台并键入localStorage。当你按Banana时,你会看到我在说什么。

您可以通过

执行此操作
localStorage.setItem( "itemName", item )
localStorage.getItem( "itemName" )

以下是源代码

<script type="text/javascript">
(function() {
        // If we arrived via a Facebook callback, it might have appended #_=_
        // to our URL. This can confuse our Backbone routers, so get rid of it.
        // http://stackoverflow.com/questions/7131909/facebook-callback-appends-to-return-url
        if (window.location.hash === "#_=_"){
            if (history.replaceState) {
                history.replaceState(null, null,
                        window.location.href.split("#")[0]);
            } else {
                window.location.hash = "";
            }
        }
    })();
</script>
相关问题